Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT – II [12 Hours]

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).

Flow Control Statements


Flow control describes the order in which statements will be executed at runtime.
Flow control statements are divided into three categories in Python.

1. Conditional Statements (or) Selection Statements


In conditional statement, based on some condition result, some group of statements will be
executed and some group of statements will not be executed.

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.

# python program to illustrate If statement


i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")

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

# python program to illustrate If else statement


i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

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

# python program to illustrate nested If statement


i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")

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

# Python program to illustrate if-elif-else ladder


i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

Output:
i is 20

Short Hand if statement


Whenever there is only a single statement to be executed inside the if block then shorthand if can
be used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")
Output:
i is less than 15

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.

# Python program to illustrate while loop


count = 0
while (count < 3):
count = count + 1
print("Hello Tom")

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

# Prints all letters except 'e' and 's'


i=0
a = 'geeksforgeeks'
while i < len(a):
if a[i] == 'e' or a[i] == 's':
i += 1
continue
print('Current Letter :', a[i])
i += 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

5. break, continue, pass and exit


i) break
 Break' in Python is a loop control statement.
 It is used to control the sequence of the loop.
 We can use break statement inside loops to break loop execution based on some
condition.

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.

Eg 1: To print odd numbers in the range 0 to 9.


for i in range(10):
if i%2==0:
continue
print(i)

1
3
5
7
9
PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 7
Another example

iii) Pass Statement


 pass statement is used to write empty loops. Pass is also used for empty control
statements, functions, and classes.
 Python pass is a null statement. When the Python interpreter comes across the pass
statement, it does nothing and is ignored.
 During execution, the interpreter, when it comes across the pass statement, ignores and
continues without giving any error.
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

iv) Python exit() function


We can also use the in-built exit() function in python to exit and come out of the program.

for val in range(0,5):


if val == 3:
print(exit)
exit()
print(val)

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 –

Sr. No. Function & Description


1 ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number x.
2 copysign(x, y)
It returns the number x and copy the sign of y to x.
3 fabs(x)
Returns the absolute value of x.
4 factorial(x)
Returns factorial of x. where x ≥ 0
5 floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.
6 fsum(iterable)
Find sum of the elements in an iterable object
7 gcd(x, y)
Returns the Greatest Common Divisor of x and y
8 isfinite(x)
Checks whether x is neither an infinity nor nan.
9 isinf(x)
Checks whether x is infinity
10 isnan(x)
Checks whether x is not a number.
11 remainder(x, y)
Find remainder after dividing x by y.

# importing "math" for mathematical operations


import math
a = 3.5
# returning the ceil of 3.5
print ("The ceil of 3.5 is : ", end="")
print (math.ceil(a))
# returning the floor of 3.5
print ("The floor of 3.5 is : ", end="")
print (math.floor(a))
# find the power
print ("The value of 3.5**2 is : ",end="")
print (pow(a,2))

# returning the log2 of 16


print ("The value of log2 of 3.5 is : ", end="")

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

a length of 1. Square brackets can be used to access elements of the string.

In computer programming, a string is a sequence of characters. For example, "hello" is a string


containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use single quotes or double quotes to represent a string in Python. For example,

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'

Access String Characters in Python


We can access the characters in a string in three ways.

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'

# access 4th last element


print(greet[-4]) # "e"

Slicing: Access a range of characters in a string by using the slicing operator colon :. For
example,
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4]) # "ell"

Python Strings are immutable


In Python, strings are immutable. That means the characters of a string cannot be changed. For
example,

message = 'Welcome'
message[0] = 'W'
print(message)

TypeError: 'str' object does not support item assignment

Python String Operations

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,

str1 = "Hello, world!"


str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)

output
False
True

In the above example,


 str1 and str2 are not equal. Hence, the result is False.

PYTHON UNIT2 NOTES (Control Structures) Faculty: Ms. Anitha/Mr. Jeelan Page 11
 str1 and str3 are equal. Hence, the result is True.

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack

Python String Length

In Python, we use the len() method to find the length of a string. For example,

greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5

Methods of Python String

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.

message = 'python is fun'


# convert message to uppercase
print(message.upper())

# Output: PYTHON IS FUN

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'

# convert message to lowercase


print(message.lower())

# Output: 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)

# Output: rot roll

find()
--------
The find() method returns the index of first occurrence of the substring (if found). If not found, it
returns -1.

message = 'Python is a fun programming language'

# check the index of 'fun'


print(message.find('fun'))

# Output: 12

rstrip()
----------
The rstrip() method returns a copy of the string with trailing characters removed (based on the
string argument passed).

title = 'Python Programming '

# remove trailing whitespace from title


result = title.rstrip()
print(result)

# Output: Python Programming

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('-'))

# Output: ['BMW', 'Tesla', 'Range Rover']

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'

# check if the message starts with Python


print(message.startswith('Python'))

# Output: True

isnumeric()
--------------
The isnumeric() method checks if all the characters in the string are numeric.

Example
pin = "523"

# checks if every character of pin is numeric


print(pin.isnumeric())

# 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'

# find the index of is


result = text.index('is')
print(result)

# Output: 7

Difference between List, Tuple, Set, and Dictionary


List Tuple Set Dictionary

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 dictionary can


The list can be Tuple can be The set can be
be represented by {
represented by [ ] represented by ( ) represented by { }
}

The Set will not The dictionary


The list allows Tuple allows duplicate
allow duplicate doesn‟t allow
duplicate elements elements
elements duplicate keys.

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

Example: {1: “a”, 2:


Example: [1, 2, 3, 4, Example: {1, 2, 3,
Example: (1, 2, 3, 4, 5) “b”, 3: “c”, 4: “d”,
5] 4, 5}
5: “e”}

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

A set is mutable i.e


A tuple is immutable
A list is mutable i.e we can make any A dictionary is
i.e we can not make
we can make any changes in the set, mutable, ut Keys are
any changes in the
changes in the list. ut elements are not not duplicated.
tuple.
duplicated.

Dictionary is
List is ordered Tuple is ordered Set is unordered ordered (Python 3.7
and above)

Creating an empty Creating an empty Creating a set Creating an empty


list Tuple a=set() dictionary
l=[] t=() b=set(a) d={}

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 = []

# Adding Element into list


l.append(5)
l.append(10)
print("Adding 5 and 10 in list", l)

# Popping Elements from list


l.pop()
print("Popped one element from list", l)
print()

# Set
s = set()

# Adding element into set


s.add(5)
s.add(10)
print("Adding 5 and 10 in set", s)

# Removing element from set


s.remove(5)
print("Removing 5 from set", s)
print()

# Tuple
t = tuple(l)

# Tuples are immutable


print("Tuple", t)
print()

# Dictionary
d = {}

# Adding the key value pair


d[5] = "Five"
d[10] = "Ten"
print("Dictionary", d)

# Removing key-value pair


del d[10]
print("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

You might also like