0% found this document useful (0 votes)
2 views

python unit 2 notes

Unit 2 covers control structures and strings in Python, detailing selective statements like if, if-else, nested if, and if-elif-else, as well as iterative statements such as for and while loops. It explains the purpose of control structures in altering program flow based on conditions and provides examples for each type of statement. Additionally, the unit includes practical exercises to reinforce understanding of these concepts.

Uploaded by

nandhakumars982
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python unit 2 notes

Unit 2 covers control structures and strings in Python, detailing selective statements like if, if-else, nested if, and if-elif-else, as well as iterative statements such as for and while loops. It explains the purpose of control structures in altering program flow based on conditions and provides examples for each type of statement. Additionally, the unit includes practical exercises to reinforce understanding of these concepts.

Uploaded by

nandhakumars982
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Unit 2

CONTROL STRUCTURES AND STRINGS

Selective statements – if, if-else, nested if, if –elif ladder statements. Iterative statements -
while, for, Nested loops, else in loops, break, continue and pass statement. Strings:
Formatting, Comparison, Slicing, Splitting, Stripping, Negative indices, String functions.

2.1 ​ CONTROL STRUCTURES


Control flow refers to the sequence a program will follow during its execution. Control Structures
are the blocks that analyze variables and choose directions in which to go based on given
parameters. They can alter the control flow of a program execution. Conditions, loops, and calling
functions influence how a Python program is controlled.
The control structures can be conditional or unconditional. The classification of control structures is
given below:

3 primary types of control structures used in Python:


 Sequential - The default working of a program
 Selection - This structure is used for making decisions by checking conditions and branching
 Repetition - This structure is used for looping, i.e., repeatedly executing a certain piece of a
code block.
1. Sequential Structure
Sequential statements are a set of statements whose execution process happens in a sequence. All
the statements are executed, one by one in sequence.
Example program: OUTPUT
a = 20 The product of 20 and 10 = 200
b = 10
c=a*b
print(f"The product of {a} and {b} = {c}”)

JCS2201 Python Programming 1Unit-2 Notes


2. Selection Structure
The statements used in selection control structures are also referred to as branching statements or
decision control statements. They are used to make decisions. They alter the flow of the program
based on the outcome of the decision. Different forms of selection statements in Python:
 Simple if
 if-else
 The nested if
 The complete if-elif-else ladder

3. Repetition Structure
Repetition structure can be used to repeat a certain set of statements. It is also called as looping
structure. Different repetition statements in Python:
 The for loop
 The while loop

2.2 SELECTIVE STATEMENTS


The statements used in selection control structures are also referred to as branching statements or
decision control statements. They are used to make decisions. They alter the flow of the program
based on the outcome of the decision.
Different forms of selection statements in Python:
 Simple if
 if-else
 The nested if
 The complete if-elif-else ladder

2.2.1 IF STATEMENT / SIMPLE IF / ONE WAY


A simple ‘if’ statement executes the statements only if the condition is true. Python if statement is
the same, as it is with other programming languages. It executes a set of statements conditionally,
based on the value of a logical expression. The statements inside the if must be indented.
Syntax: Flowchart:
if expression :
statement_1
statement_2
....
Statements outside if

JCS2201 Python Programming 2Unit-2 Notes


In the above case, expression specifies the conditions which are based on Boolean expression.
When a Boolean expression is evaluated it produces either a value of true or false. If the
expression evaluates true the same amount of indented statement(s) following if will be
executed. This group of the statement(s) is called a block.

Example: Python program to check if a number is positive or not

2.2.2 IF ELSE STATEMENT / ALTERNATIVE WAY / TWO WAY STATEMENT


Simple if statement executes the statements only if the condition is true. If the condition is false
nothing is done. But if the condition fails then we have to take an alternative path which is the else
block. If the condition is true then true block will be executed, if condition fails then else block will
be executed. The ‘if’ block and ‘else’ block statements must be indented.
Syntax: Flowchart:
if expression :
statement_1
statement_2
....
else:
statement_3
statement_4
....
Statements outside if

Example: Python program to check if a number is positive or negative

JCS2201 Python Programming 3Unit-2 Notes


2.2.3 NESTED - IF STATEMENT
Using an ‘if’ or ‘if-else’ statement inside another ‘if’ or ‘if-else’ statement is known as nested if.
The inner if condition will be checked only if outer if condition is true and so multiple conditions
have to be satisfied.
Syntax: Flowchart:
if condition1:
Statement block1
else:
if condition2:
Statement block2
else:
Statement block3
statement-outside ifn

Example: Python program to find the biggest of 3 numbers


a,b,c=map(int, input('Enter 3 values: ').split()) OUTPUT
if a>b: Enter 3 values: 20 45 33
if a>c: 45 is the biggest
print(f"{a} is the biggest")
else:
print(f"{c} is the biggest")
else:

JCS2201 Python Programming 4Unit-2 Notes


if b>c:
print(f"{b} is the biggest")
else:
print(f"{c} is the biggest")

2.2.4 IF – ELIF - ELSE LADDER STATEMENT / CHAINED / MULTIPLE ALTERNATIVES


One if statement can be placed inside another if statement or within else part to form nested if else
or if elif else. Else part will be last block and it is compulsory block. When no condition is matched
with if & if elif then finally else block will be executed.

Syntax: Flowchart:
if expression_1:
statement_block_1
elif expression_2:
statement_block_2
elif expression_3:
statement_block_3


else:
statement_block_n

In the above case, Python evaluates each expression (i.e. the condition) one by one and if a true condition is
found, the statement(s) block under that expression will be executed. If no true condition is found, the
statement(s) block under else will be executed. In the following example, we have applied if, series of elif
and else to get the grade.

Example: Python program to calculate and display the grade secured by a student based on 3 subject marks.

JCS2201 Python Programming 5Unit-2 Notes


JCS2201 Python Programming 6Unit-2 Notes
Use of and operator in if statement:
Suppose if condition has to satisfy two or more condition then we have to use and
operator to check the condition of both the expressions. If you use and operator in if
condition, then both the conditions must be true for the execution of if block. If any one
condition fails then the if block is not executed.

Truth table for AND:

Truth table for OR

Use of in operator in an if statement

JCS2201 Python Programming 7Unit-2 Notes


if-else in a single line of code

Using a negative if

JCS2201 Python Programming 8Unit-2 Notes


If a condition is true, the not operator is used to reverse the logical state. The logical not operator
will make it false.

Few Python programs using selective statements for practice:


1. Python program to input three integers and outputs the largest.
2. Python program that takes an age as input and determines whether a person is eligible to vote.
If the age is 18 or above, print “You are eligible to vote.” Otherwise, print “You are not
eligible to vote yet.”.
3. Python program to check if a number is positive, negative or zero.
4. Write a program that prompts the user to input a year and determine whether the year is a leap
year or not. Leap Years are any year that can be evenly divided by 4. A year that is evenly
divisible by 100 is a leap year only if it is also evenly divisible by 400.
5. Python program to implement a calculator.
6. Python program to read user’s age and print the corresponding age group – ‘baby’ if age is
below 1, ‘child’ if age is between 1 and 12, ‘teenager’ if age is between 13 and 19, ‘adult’ if
age is between 20 and 60 and ‘senior citizen’ if age is above 60. Accept only valid age value
7. Python program that prompts the user to input a number from 1 to 7. The program should
display the corresponding day for the given number. Example if input is 1, the output should
be ‘Sunday’.
8. Python program to calculate
electricity bill based on the given
tariff:

JCS2201 Python Programming 9Unit-2 Notes


2.3 ITERATIVE STATEMENTS
Iteration statements or loop statements allow us to execute a block of statements repeatedly as long
as the condition is true. It is also called as looping structure or repetition structure. The different
iterative statements in Python are
 The for loop
 The while loop
 Nested loops

2.3.1 FOR LOOP


Like most other languages, Python has for loops, but it differs a bit from C or Pascal. It is entry
controlled loop. In Python for loop is used to iterate over the items of any sequence including the
Python list, string, tuple etc. The for loop is also used to access elements from a container (for
example list, string, tuple) using built-in function range().
Syntax:
Method 1: General form of for loop:
for iterator_variable in sequence :
statement_block

Parameter
Name Description
Iterator_variable It indicates target variable which will set a new value for each iteration of
the loop.
A sequence of values that will be assigned to the target variable
sequence variable_name. Values are provided using a list or a string.
statement_block Set of program statements executed for each value in the sequence.

Flowchart:
For loop through a sequence

Example:

JCS2201 Python Programming 10Unit-2 Notes


Method 2: for loop with range function
Syntax:
for variable_name in range(start_value, stop_value, step_value):
statement_block

Name Description
Iterator_variable It indicates target variable which will set a new value for each iteration of the
loop. It takes values in the range start_value to stop-value – 1, incremented by
step_value after each iteration.
A sequence of values that will be assigned to the target variable
sequence variable_name. Values are provided from the built-in function range().
statement_block Set of program statements executed for each value in the range.
Flowchart:

Conditions for range function:


Start / Initial / begin value: Set the starting value for the loop. It is optional i.e., value may be

JCS2201 Python Programming 11Unit-2 Notes


omitted. The default start value is 0.
Stop / Final / End value: Set the last value for the loop. End value is mandatory to declare. The
value which you are giving as end is considered as end _value = stop_value -1
Step / Increment / Decrement value: Indicate the number of steps needed to increment or
decrement value. Default step value is +1.
Note: The above-mentioned 3 values accept only integer values not floating point values.

Python for loop and range() function


The range() function returns a list of consecutive integers. The function has one, two or three
parameters where last two parameters are optional. It is widely used in for loops.
Syntax:
range(10)  0,1,2,3,4,5,6,7,8,9
range(1, 10)  1,2,3,4,5,6,7,8,9
range(1, 10, 2)  1,3,5,7,9
range(10, 0, -1)  10,9,8,7,6,5,4,3,2,1
range(10, 0, -2)  10,8,6,4,2
range(2, 11, 2)  2,4,6,8,10
range(-5, 5)  −5,−4,−3,−2,−1,0,1,2,3,4
range(1, 2)  1
range(1, 1)  (empty)
range(1, -1)  (empty)
range(1, -1, -1)  1,0
range(0)  (empty)

Example:

JCS2201 Python Programming 12Unit-2 Notes


Example: Program to print even numbers up to n using for loop

JCS2201 Python Programming 13Unit-2 Notes


Python for loop: Iterating over tuple, list, dictionary Example: Iterating over tuple
The following example counts the number of even and odd numbers from a series of numbers.

In the above example a tuple named numbers is declared which holds the integers 1 to 9.
The best way to check if a given number is even or odd is to use the modulus operator (%). The %
operator returns the remainder when dividing two numbers.
Modulus of 8 % 2 returns 0 as 8 is divided by 2, therefore 8 is even and modulus of 5 % 2 returns
1 therefore 5 is odd.
The for loop iterates through the tuple and we test modulus of x % 2 is true or not, for every item in
the tuple and the process will continue until we reach the end of the tuple. When it is true
count_even is increased by one otherwise count_odd is increased by one. Finally, we print the
number of even and odd numbers through print statements.

Example: Iterating over list


In the following example for loop iterates through the list "datalist" and prints each item and its
corresponding Python type.

JCS2201 Python Programming 14Unit-2 Notes


Example: Iterating over dictionary
In the following example for loop iterates through the dictionary "color" through its keys and prints
each key.
color = {"c1": "Red", "c2": "Green", "c3": Output:
"Orange"} c1
for key in color: c2
print(key) c3

Following for loop iterates through its values:


color = {"c1": "Red", "c2": "Green", "c3": Output:
"Orange"} Red
for value in color.values( ): Green
print(value) Orange

An optional else clause can be attached with for statement.


Syntax:
for variable_name in sequence:
statement_block1
else:
statement_block2

The else clause is only executed after completing all the iterations in the for loop. If a break

JCS2201 Python Programming 15Unit-2 Notes


statement executes in first program block and terminates the loop then the else clause will not
execute.

2.3.2 WHILE LOOP


The basic loop structure in Python is while loop. It is an entry controlled loop. It is used to execute a
set of statements repeatedly as long as a condition is satisfied.

Syntax : Flow chart


while (expression) :
statement_block
statements_outside_while

The while loop runs as long as the expression (condition) evaluates to True and execute the
program block. The condition is checked every time at the beginning of the loop and the first time
when the expression evaluates to False, the loop stops without executing any of the remaining
statement(s). One thing we should remember that a while loop tests its condition before the body of
the loop (block of program statements) is executed. If the initial test returns false, the body is not
executed at all.

Example: Python program to find the sum of n natural number or 1 + 2 + 3 + …. + n.

JCS2201 Python Programming 16Unit-2 Notes


For example the following code never prints out anything as the condition evaluates to false.
x = 10
while (x < 5):
print(x)
x += 1

The following while loop is an infinite loop, using True as the condition:
x = 10
while True:
print(x)
x += 1

Python: while and else statement


There is a structural similarity between while and else statement. Both have a block of statement(s)
which is only executed when the condition is true. The difference is that the block belongs to if
statement executes once whereas block belongs to while statement executes repeatedly. You can
attach an optional else clause with while statement.

Syntax:
while (expression) :
statement_block1
else:
statement_block2
The while loop repeatedly tests the expression (condition) and, if it is true it executes the first block
of program statements. The else clause is only executed when the condition is false. It will not
execute if the loop breaks, or if an exception is raised. If a break statement executes in first program
block and terminates the loop then the else clause is not executed.
In the following example, while loop calculates the sum of the integers from 0 to 9 and after
completing the loop, the else statement executes.

JCS2201 Python Programming 17Unit-2 Notes


Example: Python program to find the sum of first n natural numbers

2.3.3 NESTED LOOPS


Using a loop inside another loop is called as nested loops. For example, while loop inside the for
loop, for loop inside the for loop, etc. The inner loop will be executed one time for each iteration of
the outer loop. Hence all the iterations of the inner loop are executed for every iteration of the outer
loop.
Syntax:
For loop inside for loop While inside while loop While loop inside for loop
for iterator_variable1 in while condition1: for iterator_variable1 in
sequence1: outer_loop_block1 sequence1:
outer_loop_block1 outer_loop_block1
while condition2:
for iterator_variable2 in inner_loop_block while condition:
sequence2: inner_loop_block
inner_loop_block outer_loop_block2
outer_loop_block2
outer_loop_block2

Nested for loop

JCS2201 Python Programming 18Unit-2 Notes


Nested while loop

Example programs:
Nested for loop
for i in range(5): OUTPUT
for j in range(3): 0 1 2
print(j, end = ‘ ‘) 0 1 2
print() 0 1 2
0 1 2
0 1 2
Nested while loop

i=1 OUTPUT
while i<=4: 1
j=1 1 2
while j<=i:
1 2 3
print(j, end=' ')
j+=1 1 2 3 4
i+=1
print()

2.3.4 BREAK STATEMENT


The break statement is an unconditional statement. It can alter the flow of execution of normal loop
because of some external condition. It is mainly used to terminate a for or a while loop. The purpose
of this statement is to end the execution of the loop (for or while) immediately and the program
control goes to the statement after the last statement of the loop. If there is an optional else
statement in while or for loop it skips the optional clause also. When break statement is encountered
then the control of the current loop is exited.

Syntax: Flowchart:

JCS2201 Python Programming 19Unit-2 Notes


Example: break in while loop
In the following example while loop breaks when the count value is 15.

Example: using break in for loop


In the following example for loop breaks when the count value is 5.

JCS2201 Python Programming 20Unit-2 Notes


2.3.5 CONTINUE STATEMENT

The continue statement is used in a while or for loop to take the control to the top of the loop
without executing the iteration inside the loop. Usually continue does not terminate the loop
execution
Syntax: continue

Syntax: Flowchart:

JCS2201 Python Programming 21Unit-2 Notes


Example: Python program using continue

In the above example, the for loop prints all the numbers from 0 to 6 except 3 and 6 as the continue
statement returns the control of the loop to the top.

2.3.6 PASS STATEMENT


In Python programming, pass is a null statement. The difference between a comment and
pass statement in Python is that, the interpreter ignores a comment entirely whereas pass
is not ignored. However, nothing happens when pass is executed. It results into no
operation (NOP).
Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. It cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.

Syntax: pass

Example program using pass

JCS2201 Python Programming 22Unit-2 Notes


ILLUSTRATIVE PROGRAMS:
1. Example program for swapping two numbers:

JCS2201 Python Programming 23Unit-2 Notes


2. Python program to check if the input year is a leap year or not

3. Python program to find distance between two points:

JCS2201 Python Programming 24Unit-2 Notes


Few Python programs using looping statement for practice:
1. Python program to display the first n natural numbers.
2. Python program to display the first n natural numbers in reverse.
3. Python program to display the even numbers in the range 1 to n.
4. Python program to find the sum of first n natural numbers.
5. Python program to find the sum of n natural numbers.
6. Python program to find the factorial of a number.
7. Python program to find the exponent of a number - an.
8. Python program to display the multiplication table of a number.
9. Python program to display the Fibonacci series.
10. Python program to find the sum of digits of a number.
11. Python program to find the reverse of a number.
12. Python program to check if a number is palindrome or not.
13. Python program to check if a number is Armstrong number or not.
14. Python program to check if a number is prime number or not.

2.4 STRINGS
A String is a data structure in Python that represents a sequence of characters (alphabets, numbers
and symbols). It is an immutable data type, meaning that once you have created a string, you cannot
change it. Strings are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented as text.
Python does not have a character data type, a single character is simply a string with a length of 1.
A string is enclosed within ‘ ’ or “ ” or ‘‘‘ ’’’
Eg.
>>> name = “Kannan”
>>> gr = ‘A’
>>> dept = ‘ECE’
>>> employee_id = “IOB157”
>>> print(“My name is “, name)
My name is Kannan
>>> print(name + ” scored” + gr + “ grade”)
Kannan scored A grade
>>>
Accessing Characters in a String
In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String, e.g. -1
refers to the last character, -2 refers to the second last character, and so on.

While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be
passed as an index, float or other types that will cause a TypeError.

JCS2201 Python Programming 25Unit-2 Notes


Example: The string “PYTHON PROGRAM” can be indexed and accessed as shown below:

Character P Y T H O N P R O G R A M
s
Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13

>>> str1 = ‘PYTHON PROGRAM’


>>> print(str1)
PYTHON PROGRAM
>>> print(str1[2])
T
>>> str1[3] = 'G'
TypeError: 'str' object does not support item assignment

Deleting/Updating from a String


This will cause an error because item assignment or item deletion from a String is not supported.
Although deletion of the entire String is possible with the use of a built-in del keyword. This is
because Strings are immutable, hence elements of a String cannot be changed once assigned. Only
new strings can be reassigned to the same name.

Updating / deleting an entire string


As Python strings are immutable in nature, the existing string cannot be updated. It can only
assigned a completely new value to the variable with the same name. It can be deleted only using
del( ) method.

Example:
str1 = 'PYTHON PROGRAM' Output
print(str1) PYTHON PROGRAM
Java code
str1 = ‘’Java code’ # str1 updated with new value name 'str1' is not defined
print(str1)

del(str1) # str1 deleted


print(str1)

Updating a character
A character of a string can be updated in Python by using any of the 2 methods:
(i) By converting the string into a Python List and then updating the element in the list. As lists are
mutable in nature, we can update the character and then convert the list back into the String.

JCS2201 Python Programming 26Unit-2 Notes


Example:
str1 = 'PYTHON PROGRAM' Output
print(str1) PYTHON PROGRAM
list1 = list(str1) PYTHOG PROGRAM
list1[5] = 'G'
str1 = ''.join(list1)
print(str1)

(ii) By using the string slicing method. Slice the string before the character to be updated, then add
the new character and finally add the other part of the string again by string slicing.

2.4.1 FORMATTING
String formatting allows to create dynamic strings by combining variables and values. There are
five different ways to perform string formatting in Python.
1. Formatting with % Operator.
2. Formatting with format() string method.
3. Formatting with string literals, called f-strings.
4. Formatting with center() string method.

1. Formatting with % Operator


Here the modulo % operator is used. The modulo %s is also known as the “string-formatting
operator”. It acts like a placeholder for a string or string variable.

Example code Output


print("I %s for ice cream" %'scream') I scream for ice cream
#%s will be replaced by ‘scream’

print("I %s for ice %s"%('scream', 'cream')) I scream for ice cream


#the first %s will be replaced by ‘scream’ and
the next %s will be replaced by ‘cream’

a = ‘scream’ I scream you scream for ice cream


print("I %s you %s for ice %s "%(a, a,
‘cream’))
# %s will be replaced by the values and the
variables provided inside ( ), in order

2. Formatting with format() string method

JCS2201 Python Programming 27Unit-2 Notes


Format() method was introduced with Python for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders defined
by a pair of curly braces { } into a string and calling the str.format(). The value to be put into the
placeholders and concatenated with the string are passed as parameters into the format function.

Examples:
Example code Output
print('Apple is {} in color' . format('red')) Apple is red in color

#{} is the placeholder for the argument ‘red’ in


format method
print(‘{2} is {0} in {1}’ . format('red', ‘color’, Apple is red in color
‘Apple’))

#the numbered placeholders {} are used and


the numbers indicate the index values for the
arguments in format( ) method
print("{a} is {a} in {b}” . format(a=’orange’, orange is orange in color
b=’color’))

# the named placeholders {} are used and the


numbers indicate the positions where the
corresponding named arguments will be placed
– same name can be reused

3. Formatting with string literals, called f-strings.


To create an f-string in Python, prefix the string with the letter “f”. The string itself can be
formatted in much the same way that you would with str. format().
F-strings provide a concise and convenient way to embed Python expressions inside string literals
for formatting. F-string is written as f”string”

Examples:
Example code Output
a = 'Kevin' His name is Kevin.
print(f"His name is {a}.")

#{} is the named placeholder which has the


name of the variable and it is replaced by the
variable’s value

JCS2201 Python Programming 28Unit-2 Notes


a=5 He said his age is 30.
b = 10
print(f"He said his age is {2 * (a + b)}.")

# the f-string is used to evaluate and display the


result of an expression
print("{a} is {a} in {b}” . format(a=’orange’, orange is orange in color
b=’color’))

# the named placeholders {} are used and the


numbers indicate the positions where the
corresponding named arguments will be placed
– same name can be reused

f-string formatting can also be used to interpolate the value of a float variable into the string.

Syntax: {value : .precisionf} where .precisionf indicates the number of digits after the decimal
point.
Example:
Example code Output
num = 3.1428571428 The value of pi is: 3.14286

print(f"The value of pi is: {num : .5f}")


4. Formatting with center() string method.
The center() method is a built-in method in Python’s str class that returns a new string that is
centered within a string of a specified width. The string will be padded with spaces on the left and
right sides.
Example code Output
s = "Python Programming" Python Programming
width = 30
centered_string = s.center(width)
print(centered_string)
Totally a space of width 30 is allocated and the string is centered in that space.

2.4.2 NEGATIVE INDICES


Negative indexes refer to the positions of elements within an array-like object such as a string (or
list or tuple), counting from the end of the data structure rather than the beginning.

For example, in a string with 5 characters, the last character can be accessed using the index -1, the
second to last element using the index -2, and so on. Negative indexes can be useful for accessing

JCS2201 Python Programming 29Unit-2 Notes


elements from the end of a data structure without having to know the exact length of the data
structure.

Negative indexing can be used in string slicing.


Example:
Character o r a n g e t r e e
s
Index 0 1 2 3 4 5 6 7 8 9 10
-ve Index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

>>>str = ‘orange tree’


>>>print(str[-4])
t

2.4.3 COMPARISON
Python string comparison methods are used to compare strings. However, Python also comes with a
few inbuilt operators to facilitate string comparison. All these comparison methods return a boolean
true or false.

String comparison using operators:


The ‘==’ and ‘!=’ are commonly used relational operators for python string comparison. These
operators compare Unicode values of all the elements in the string and return either a boolean true
or false. Apart from them, the identity operators ‘is’ and ‘is not’ can also be used for string
comparison.

The "==" is a python string comparison method that checks if both the values of the operands are
equal. This operator is the most commonly used method to check equality in python.
The ‘==’ operator returns True if the two strings compared are the same; otherwise it returns False.

The != is another python string comparison operator that checks if the values of the operands are
not equal. It performs the opposite of == operator.
The ‘!=’ operator returns True if the two strings compared are not the same; otherwise it returns
False.

Example code Output


s1 = "Stationary" True
s2 = ‘Stationary’ False
s3 = ‘Stationery’ Strings Stationary and Stationery
print(s1 == s2) are different
print(s1 == s3)

JCS2201 Python Programming 30Unit-2 Notes


if s2==s3:
print(f“Strings {s2} and {s3} are the same”)
else:
print(f“Strings {s2} and {s3} are different”)
s1 = "Stationary" False
s2 = ‘Stationary’ True
s3 = ‘Stationery’ Strings Stationary and Stationary
print(s1 != s2) are the same
print(s1 != s3)
if s1 != s2:
print(f“Strings {s1} and {s2} are different”)
else:
print(f“Strings {s1} and {s2} are the same”)

Using ‘is’ and ‘is not’ The ‘is’ and ‘is not’ operators are similar to ‘==’ and ‘!=’ respectively.
However, unlike the relational operators, is and is not compares to the Identity (id) of the objects
and returns true if they share the same identity.
Two objects are the same when they have the same identity and share the same memory location.
But if he object is given another value the memory allocation changes giving it a new identity.
The ‘is’ operator returns True if the two objects compared are the same; otherwise it returns False.
The ‘is not’ operator returns True if the two objects compared are different; otherwise it returns
False.
Example and output:
>>>s1 = 'greek' >>>s2 = 'latin'
>>>s2 = 'greek' >>>print(id(s2))
>>>s3 = 'latin' 140105907647216
>>>print(id(s1)) >>>print(s1 is s2)
140105907644848 False
>>>print(id(s2)) >>>print(s2 is s3)
140105907644848 True
>>>print(id(s3)) >>> print(s1 is not s3)
140105907647216 True
>>>print(s1 is s2) >>> print(s2 is not s3)
True False
>>>print(s2 is s3)
False

2.4.4 SLICING
 Python slicing is a process of obtaining a sub-string from the given string by slicing it
respectively from start to end.

JCS2201 Python Programming 31Unit-2 Notes


 Python string is immutable, slicing creates a new substring from the source string and original
string remains unchanged.
 Python slicing can be done in two ways:
 Using a slice() method
 Using the array slicing [:: ] method

Method-1 Using the slice() method


The slice() constructor creates a slice object representing the set of indices specified by range(start,
stop, step).

Syntax:
 slice(stop_pos)  slice created from characters in 0th to (stop_pos - 1)th positions
 slice(start_pos, stop_pos, step)  slice created from characters in 0th to (stop_pos - 1)th
positions, incremented by step number of positions
start_pos: Starting index where the slicing of object starts.
stop_pos: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.

Eg. str = “orange tree”


Character o r a n g e t r e e
s
Index 0 1 2 3 4 5 6 7 8 9 10
-ve Index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

>>>s1 = slice(3) # slice created from 0th character to 2nd character


>>>s2 = slice(1, 5, 1) # slice created from 1st character to 4th character
>>>s3 = slice(1, 8, 2) # slice created from 1st , 3rd, 5th, and 7th characters
>>>s4 = slice(-1, -12, -2) # slice created from (-1)th character (last) to (-11)th character
.>>>print(str[s1])
ora
>>>print(str[s2])
rang
>>>print(str[s3])
rnet
>>>print(str[s4])
er gao

Method-2 Using the array slicing [: : ] method


A substring is created by using the set of indices specified by range(start, stop, step).

JCS2201 Python Programming 32Unit-2 Notes


Syntax: str_object[start_pos : end_pos : step]
start_pos: Starting index where the slicing of object starts.
stop_pos: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.

Example:
Character o r a n g e f r u i t
s
Index 0 1 2 3 4 5 6 7 8 9 10 11
-ve Index -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

>>> s = “orange fruit” >>>print(s[ 3 : ]) >>>print(s[ : : -1])


>>>print(s[ : ]) nge fruit tiurf egnaro
orange fruit >>>print(s[2 : 8]) >>>print(s[8 : 1 : -1])
>>>print(s[ : : ] ange f rf egna
orange fruit >>>print(s[2 : 11 : 2]) >>>print(s[8 : 1 : -2])
>>>i = 5 ag ri r ga
>>>print(s[ : i ] + s[ i : ]) >>>print(s[30 : ]) >>>print(s[-3 : -10])
orange fruit urf egn
>>>print(s[ : 5]) >>>print(s[4 : 50]) >>>print(s[-4 : -2])
orang ge fruit ge fru

2.4.5 SPLITTING
String splitting is a process of splitting a string into a list of strings after breaking the given string
by the specified separator.
It is done using split( ) method. split( ) method breaks down a string into a list of substrings using a
chosen separator. Default separator is any whitespace.

Syntax: string.split(separator, maxsplit)


Separator  Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator.
Maxsplit  Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences". If maxsplit is specified, the list will have a maximum of maxsplit+1 items.

Example:
>>> text = "Apple is good for health" >>>text = 'one, two, three, four, five, six'
>>>print(text.split()) >>>print(text.split(',', 0))
# default separator is whitespace ['one, two, three, four, five, six']

JCS2201 Python Programming 33Unit-2 Notes


['Apple', 'is', 'good', 'for', 'health']
>>>text = ‘one, two, three’ >>>text = 'one, two, three, four, five, six'
>>>print(text.split(',')) >>>print(text.split(',', 4))
['one', ' two', ' three'] ['one', ' two', ' three', ' four', ' five, six']
# if maxsplit = 4, the string is split at each
occurrence of the delimiter, up to a maximum
of 4 splits, resulting in 5 elements in list
>>>text = ‘apple#banana#cherry#orange’ >>>text = 'one, two, three, four, five, six'
>>>print(text.split(‘#’) >>>print(text.split(',', 1))
['apple', 'banana', 'cherry', 'orange'] ['one', ' two, three, four, five, six']
# if maxsplit = 1, the string is split at each
occurrence of the delimiter, up to a maximum
of 1 split, resulting in 2 elements in list
>>>word = 'CatBatSatFatOr'
>>>print(word.split('t'))
['Ca', 'Ba', 'Sa', 'Fa', 'Or']

When split( ) method is used to split a text into a list of elements, based on the separator (or)
delimiter, join( ) method can be used to construct a text from a list elements.
Eg.
>>>text = ‘apple#banana#cherry#orange’ >>>new_text = ‘, ‘.join(list1)
>>>list1 = text.split(‘#’) >>>print(new_text)
>>>print(list1) apple, banana, cherry, orange
['apple', 'banana', 'cherry', 'orange']

Example program: Python program to verify if the email id is a valid gmail id or not
text = input("Enter your email id: ") Output:
list1 = text.split('@') Enter your email id: [email protected]
if list1[1] =='gmail.com': Email id verified..
print("Email id verified..")
else: Output 2:
print("It is not a valid gmail id ") Enter your email id: [email protected]
It is not a valid gmail id

2.4.6 STRIPPING
Stripping is a process of removing extra whitespaces and specified characters from the start and
from the end of the strip irrespective of how the parameter is passed.
It is done using strip( ) method in Python. This method returns a copy of the string with both leading and
trailing characters removed.

JCS2201 Python Programming 34Unit-2 Notes


Purpose of strip( ) method
When a developer wishes to remove characters or whitespaces from the beginning or end of a
string, the Strip() function in Python comes in use.

Syntax: string.strip(characters)
Characters  optional parameter. A set of characters to remove as leading / trailing characters.

Example:
>>>string = " Hello, world! "
>>>new_string = string.strip()
>>>print(new_string)
Hello, world! # output

>>>string1 = ' xxxx oooo hello xxox ee '


>>>print(string1.strip(' xoe')) # all <whitespace>,x,o,e characters in the left # and right of
# string are removed
hell # output

2.4.7 STRING FUNCTIONS


Python has a set of built-in methods that can be used on strings.
S.No. Method Description
1 capitalize() Converts the first character to upper case
2 casefold() Converts string into lower case
3 center() Returns a centered string
4 count() Returns the number of times a specified value occurs in a string
5 endswith() Returns true if the string ends with the specified value
6 find() Searches the string for a specified value and returns the position of
where it was found
7 format() Formats specified values in a string
8 index() Searches the string for a specified value and returns the position of
where it was found
9 isalnum() Returns True if all characters in the string are alphanumeric
10 isalpha() Returns True if all characters in the string are in the alphabet
11 isascii() Returns True if all characters in the string are ascii characters
12 isdecimal() Returns True if all characters in the string are decimals
13 isdigit() Returns True if all characters in the string are digits
14 isidentifier( Returns True if the string is an identifier
)
15 islower() Returns True if all characters in the string are lower case
16 isnumeric() Returns True if all characters in the string are numeric

JCS2201 Python Programming 35Unit-2 Notes


17 isspace() Returns True if all characters in the string are whitespaces
18 istitle() Returns True if the string follows the rules of a title
19 isupper() Returns True if all characters in the string are upper case
20 join() Converts the elements of an iterable into a string
21 ljust() Returns a left justified version of the string
22 lower() Converts a string into lower case
23 replace() Returns a string where a specified value is replaced with a specified
value
24 rfind() Searches the string for a specified value and returns the last position of
where it was found
25 rindex() Searches the string for a specified value and returns the last position of
where it was found
26 rjust() Returns a right justified version of the string
27 split() Splits the string at the specified separator, and returns a list
28 startswith() Returns true if the string starts with the specified value
29 strip() Returns a trimmed version of the string
30 swapcase() Swaps cases, lower case becomes upper case and vice versa
31 title() Converts the first character of each word to upper case
32 upper() Converts a string into upper case
33 zfill() Fills the string with a specified number of 0 values at the beginning

JCS2201 Python Programming 36Unit-2 Notes

You might also like