Unit2 Python Students
Unit2 Python Students
Control Structures: Decision making statements, Python loops, Python control statements.
Python Native Data Types: Numbers, Lists, Tuples, Sets, Dictionary, Functions & Methods of
Dictionary, Strings (in detail with their methods and operations).
Note: There is no switch statement in Python. (Which is available in C and Java). Instead we
have match-statement.
There is no do-while loop in Python.(Which is available in C and Java)
goto statement is also not available in Python. (Which is available in C)
i) if Statement :
if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
We
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 1
can use condition with bracket „(„ „)‟ also.
As we know, python uses indentation to identify a block. So the block under an if statement will
be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is
executed.
if-else
The if statement alone tells us that if a condition is true it will execute a block of statements and
if the condition is false it won‟t. But what if we want to do something else if the condition is
false.
Here comes the else statement. We can use the else statement with if statement to execute a block
of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Output:
i is greater than 15
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 2
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if
statement is false after calling the statement which is not in block(without spaces).
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements mean
an if statement inside another if statement. Yes, Python allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Output:
i is smaller than 15
i is smaller than 12 too
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 3
statement
Output:
i is 20
2. while statement
Python While Loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately after the
loop in the program is executed.
Syntax:
while expression:
statement(s)
While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn‟t specified explicitly in advance.
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 4
Statements represent all the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements. When a while loop is executed, expr
is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the
expr is checked again, if it is still true then the body is executed again and this continues
until the expression becomes false.
Output
Hello Tom
Hello Tom
Hello Tom
# checks if list still contains any element
a = [1, 2, 3, 4]
while a:
print(a.pop())
Output
4
3
2
1
Output:
Current Letter :g
Current Letter :k
Current Letter :f
Current Letter :o
Current Letter :r
Current Letter :g
Current Letter :k
3. for statement
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 5
dictionary, a set, or a string).
for itarator_variable in sequence_name:
Statements
...
Statements
The first word of the statement starts with the keyword “for” which signifies the
beginning of the for loop.
• Then we have the iterator variable which iterates over the sequence and can be
used within the loop to perform various functions
• The next is the “in” keyword in Python which tells the iterator variable to loop for
elements within the sequence
• And finally, we have the sequence variable which can either be a list, a tuple, or any
other kind of iterator.
• The statements part of the loop is where you can play around with the iterator
variable and perform various function
Example 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Example 2:
for x in "cherry":
print(x)
4. match-case statement
• To implement switch-case and if-else functionalities A match statement will compare a given
variable‟s value to different cases, also
referred to as the pattern.
• The main idea is to keep on comparing the variable with all the present patterns until it fits into
one.
Syntax of match-case:
match variable_name:
case ‘pattern1’ : //statement1
case ‘pattern2’ : //statement2
…
case ‘pattern n’ : //statement n
Example 1:
quit_flag = False
match quit_flag:
case True:
print("Quitting")
exit()
case False:
print("System is on")
Output:
System is on
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 6
Example 2:
def calc(n:int):
return (n**2)
def calc(n:float):
return (n**3)
n = 9.5
is_int = isinstance(n, int)
match is_int:
case True : print("Square is :",calc(n))
case False : print("Cube is:", calc(n))
Output:
Cube is: 857.375
EXAMPLE:
i=0
for i in range(5):
if i == 3:
break
print(i)
Output
0
1
2
ii) continue:
It is used to control the sequence of the loop.
Continue statement skips the remaining lines of code inside the loop and brings the
program control to the beginning of the loop.
1
3
5
7
9
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 7
Another example
Another example:
# An empty loop
a = 'presidency'
i=0
while i < len(a):
i += 1
pass
print('Value of i :', i)
Output:
Value of i : 10
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 8
After writing the above code (python exit() function), Ones you will print “ val ” then the output
will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to
exit, and it will print the exit message too.
Python Mathematics
The math module of Python helps to carry different mathematical operations trigonometry,
statistics, probability, logarithms, etc.
Numbers and Numeric Representation
These functions are used to represent numbers in different forms. The methods are like below –
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 9
print (math.log2(a))
# print the square root of 3.5
print ("The value of sqrt of 3.5 is : ", end="")
print(math.sqrt(a))
# returning the value of sine of 3.5
print ("The value of sine of 3.5 is : ", end="")
print (math.sin(a))
end="" - The end parameter in the print function is used to add any string. At the end of the
output of the print statement in python.
Output
The ceil of 3.5 is : 4
The floor of 3.5 is : 3
The value of 3.5**2 is : 12.25
The value of log2 of 3.5 is : 1.8073549220576042
The value of sqrt of 3.5 is : 1.8708286933869707
The value of sine of 3.5 is : -0.35078322768961984
2. STRINGS
Indexing: One way is to treat strings as a list and use index values. For example,
greet = 'hello'
# access 1st index element
print(greet[1]) # "e"
Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For example,
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 10
greet = 'hello'
Slicing: Access a range of characters in a string by using the slicing operator colon :. For
example,
greet = 'Hello'
message = 'Welcome'
message[0] = 'W'
print(message)
There are many operations that can be performed with strings which makes it one of the most
used data types in Python.
1. Compare Two Strings
We use the == operator to compare two strings. If two strings are equal, the operator
returns True. Otherwise, it returns False. For example,
output
False
True
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 11
str1 and str3 are equal. Hence, the result is True.
In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)
In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'
# Output: 5
Besides those mentioned above, there are various string methods present in Python. Here are
some of those methods:
Methods Description
upper()
------------
The upper() method converts all lowercase characters in a string into uppercase characters and
returns it.
lower()
--------
The lower() method converts all uppercase characters in a string into lowercase characters and
returns it.
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 12
message = 'PYTHON IS FUN'
replace()
----------
The replace() method replaces each matching occurrence of a substring with another string.
text = 'bat ball'
# replace 'ba' with 'ro'
replaced_text = text.replace('ba', 'ro')
print(replaced_text)
find()
--------
The find() method returns the index of first occurrence of the substring (if found). If not found, it
returns -1.
# Output: 12
rstrip()
----------
The rstrip() method returns a copy of the string with trailing characters removed (based on the
string argument passed).
split()
--------
The split() method splits a string at the specified separator and returns a list of substrings.
Example
cars = 'BMW-Telsa-Range Rover'
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 13
# split at '-'
print(cars.split('-'))
startswith()
-------------
The startswith() method returns True if a string starts with the specified prefix(string). If not, it
returns False.
Example
message = 'Python is fun'
# Output: True
isnumeric()
--------------
The isnumeric() method checks if all the characters in the string are numeric.
Example
pin = "523"
# Output: True
index()
---------
The index() method returns the index of a substring inside the string (if found). If the substring is
not found, it raises an exception.
Example
text = 'Python is fun'
# Output: 7
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 14
List Tuple Set Dictionary
A list is a non-
A Tuple is also a non- The set data
homogeneous data A dictionary is also
homogeneous data structure is also a
structure that stores a non-homogeneous
structure that stores non-homogeneous
the elements in data structure that
elements in columns of data structure but
columns of a single stores key-value
a single row or stores the elements
row or multiple pairs.
multiple rows. in a single row.
rows.
The list can use Tuple can use nested The set can use The dictionary can
nested among all among all nested among all use nested among all
A setA
A list can be created Tuple can be created A dictionary can be
dictionary can be
using using created using
created using
the list() function the tuple() function. the dict() function.
the set() function
Dictionary is
List is ordered Tuple is ordered Set is unordered ordered (Python 3.7
and above)
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 15
# Python3 program for explaining
# use of list, tuple, set and
# dictionary
# Lists
l = []
# Set
s = set()
# Tuple
t = tuple(l)
# Dictionary
d = {}
Output:
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 16
Adding 5 and 10 in list [5, 10]
Popped one element from list [5]
Adding 5 and 10 in set {10, 5}
Removing 5 from set {10}
Tuple (5,)
Dictionary {5: 'Five', 10: 'Ten'}
Dictionary {5: 'Five'}
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 17