python unit 2 notes
python unit 2 notes
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.
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
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.
Using a negative if
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:
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:
Example:
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.
The else clause is only executed after completing all the iterations in the for loop. If a break
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.
The following while loop is an infinite loop, using True as the condition:
x = 10
while True:
print(x)
x += 1
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.
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()
Syntax: Flowchart:
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:
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.
Syntax: pass
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.
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
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)
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.
(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.
Examples:
Example code Output
print('Apple is {} in color' . format('red')) Apple is red in color
Examples:
Example code Output
a = 'Kevin' His name is Kevin.
print(f"His name is {a}.")
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
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
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.
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.
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.
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.
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
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.
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']
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.
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