Control Structures in Python
Control Structures in Python
UNIT – 2
Control Structures
Agenda
Selection Statements
if statement, if-else statement
if-elif-else statement, nested-if statement
Iterative Statements
while loop, for loop
break statement, continue statement
pass and else statements used with loops
Selection Statements
if statement
Decisions can be taken depends on the condition by the
selection statements.
if statement
if else statement
nested if statement
if elif statement
switch case statement
if statement
It will check the given condition, if it is true then only
take some actions
Syntax
if(condition) :
suite_statement(s)
Flow Control
True
if(condition)
Suite
statement(s)
if statement
Examples
suite1 Suite2
statement(s) statement(s)
if else statement
Examples
False True
if(cond-1)
Suite1
False True statement(s)
elif(cond-2)
Suite2
False True statement(s)
elif(cond-3)
suite3
statement(s)
suiteN
statement(s)
Nested if elif statement
Example
dgt = 2
if(dgt == 0) :
chr = ‘Zero’
print(chr)
elif(dgt == 1) :
chr = ‘One’
print(chr)
elif(dgt == 2) :
chr = ‘Two’
print(chr)
else :
print('Enter 0-2 only...')
Switch case statement
Python language does not have switch statement.
Use the other alternatives for the switch case statement
functionality and make the programming easier and
faster.
3 different techniques are there to implement switch case
functionality.
1. If-elif-else
2. Dictionary Mapping
3. Using classes
Practice Script Exercises
20. WAS to find the given number is odd/even
21. WAS to find a given is leap year or not
22. WAS to find the biggest of 2 numbers
23. WAS to find the smallest of 2 numbers
24. WAS to find the biggest of 3 numbers
25. WAS to find the smallest of 3 numbers
26. WAS to print the ASCII value of given character.
27. WAS to find whether the given character is lower case / not
28. WAS to find whether the given character is upper case / not
29. WAS to find the whether the given character is vowel / not
30. WAS to convert the character lower case into upper case
31. WAS to convert string upper case into lower case
32. WAS to find whether the given character is arithmetic operator or not
Nested if..else
32. WAS to find whether given no. is single digit /double / three / four /not.
33. WAS to find whether the given character is upper case / lower / digit/ special character
while statement
for .. in statement
While Statement
False
while(cond) :
True
[ else :
suite
suite statement(s) ]
statement(s)
Examples
(1)
n = int(input('How many times want to print SVEC : '))
cnt = 1
while(cnt <= n) :
print('SVEC')
cnt += 1
(2)
n = int(input('How many times want to print SVEC : '))
cnt = 1
while(cnt <= n) :
print('SVEC')
cnt += 1
else :
print('Printing college name tasks is over')
Practice Script Exercises
36. WAS to print the natural number up to n
37. WAS to print odd or even number between 1 to n.
38. WAS to print the sum of numbers up to N
39. WAS to print the sum of odd numbers up to N
40. WAS to print the sum of even numbers up to N
41. WAS to print the factorial of given number N.
42. WAS to accept the lower and upper limit of year then print the leap year or
not leap year.
43. Write program to count the number of positive, negative and Zero until
press -1000.
44. WAS to calculate and print the sum of first N terms of the following series.
Sum = 1 + (1+2)+(1+2+3)+(1+2+3+...+n)
45. WAS to calculate and print the sum of first N terms of the following series.
Sum = 1 + (1*2)+(1*2*3)+(1*2*3*...*n)
for .. in Statement
for .. in loop is used for sequential traversal.
It is used for iterating over an iterable like string, range,
tuple, list, set, dictionary.
It falls under the category of definite iteration.
Definite iterations mean the number of repetitions is
specified explicitly in advance.
NOTE
There is no C style for loop, i.e., for (i = 0; i < n; ++i)
False
Is
Next If No more elements in sequence
element in
sequence
?
True
[ else :
suite statement(s) ]
Examples
(1)
for num in [0, 1, 2, 3, 4] :
print(num)
(2)
for num in list(range(5)) :
print (num)
(3)
for chr in 'SVEC' : # traversal of a string sequence
print ('Current Letter : ', chr)
Examples
(4)
AP_Cities = ['Tirupati', 'Chitoor', 'Nellore']
for citynm in AP_Cities : # traversal of List sequence
print('Current City : ', citynm)
else :
print('All City Names are Printed\n')
(5)
#traversal of List sequence with index
AP_Cities = ['Tirupati', 'Chitoor', 'Nellore']
for index in range(len(AP_Cities)) :
print('Current City [', index, '] : ', AP_Cities[index])
else :
print('All City Names are Printed with its index\n')
Examples
(6)
Lstnum = [11,13,15,20,17,19] #[11,13,15,17,19]
for n in Lstnum:
if n % 2 == 0 :
print('the list contains an even number')
break
else:
print('the list does not contain even number')
Iterator and Generator
Iterator is an object which allows to traverse through all the
elements of a collection.
Iterator object implements in two methods,
iter() and next().
String, List or Tuple objects can be used to create an Iterator.
Example Script
# Prg 37 , Prg for visit iterator elements using next() and for..in 14/11/2021
import sys
list = [1, 2, 3, 4]
lel = iter(list) # this builds an iterator object
#prints next available element in iterator
print('Next Available Element : ', next(lel))
#Iterator object can be traversed using for..in statement
for e in lel:
print(e, end=" ")
Examples
#Prg 38, Prg for visit iterator elements using next() and try
except 14/11/2021
import sys
list = [1, 2, 3, 4]
lel = iter(list)
while True:
try:
print (next(lel))
except StopIteration:
sys.exit()
Iterator and Generator
A generator is a function that produces or yields a sequence
of values using yield method.
When a generator function is called, it returns a generator
object without even beginning execution of the function.
When the next() method is called for the first time, the
function starts executing until it reaches the yield statement,
which returns the yielded value.
The yield keeps track i.e. remembers the last execution and
the second next() call continues from previous value.
Iterator and Generator
#Prg 39 Prg for Fibonacci Series using and iterator 14/11/2021
import sys
def fibonacci(num): #generator function, creating f is an iterator object
n1, n2, cnt = 0, 1, 0 #a, b, cnt = 0, 1, 0
while True:
if(cnt > num):
return
yield n1
n1 = n2
n2 = n1 + n2
cnt += 1
Iterator and Generator
#Driver Code
n = int(input('Enter a Number : '))
f = fibonacci(n)
print('\nFibonacci Series of ', n)
while True:
try :
print(next(f), end=" ")
except StopIteration:
sys.exit()
Iterator and Generator
#Prg 40, Prg for various iterator with for .. in 14/11/2021
# Iterating on a tuple (immutable)
print("\nIteration of Tuple")
sdt = ("15678", "II BTech", "CSE")
for el in sdt :
print(el)
# Iteration on a String
print("\nIteration of String")
cname = "SVEC"
for ch in cname :
print(ch, end='')
# Iterating on dictionary
print("\n\nIteration of Dictionary")
dindx = dict()
dindx['learning'] = 140
dindx['python'] = 270
for el in dindx :
print("% s % d" % (el, dindx[el]))
Iterator and Generator
#Prg 41, Prg for various iterator with for .. in 14/11/2021
# Iterating on a tuple (immutable)
print("\nIteration of Tuple")
sdt = ("15678", "II BTech", "CSE")
for el in sdt :
print(el)
# Iteration on a String
print("\nIteration of String")
cname = "SVEC"
for ch in cname :
print(ch, end='')
# Iterating on dictionary
print("\n\nIteration of Dictionary")
dindx = dict()
dindx['learning'] = 140
dindx['python'] = 270
for el in dindx :
print("% s % d" % (el, dindx[el]))
Loop Control Statements
The Loop control statements change the execution from its normal
sequence.
When the execution leaves a scope, all automatic objects that were
created in that scope are destroyed.
Python supports the following control statements.
continue statement
It skip all statement of its body and move to the condition .
pass statement
The pass statement to write empty loops. Pass is also used for empty
control statements, functions, and classes.
Continue Statement
#Prg 42, Prg for Print all characters except '$' and '#‘, 14/11/2021
for chr in 'Mac$hin#e' :
if chr == '$' or chr == '#':
continue
print(chr, end = '')
print('\r')
#Prg 43, Prg to check even number is there or not in a list, 14/11/2021
Lstnum = [11,13,15,17,19] #[11,13,15,20, 17,19]
for n in Lstnum :
if(n % 2 == 0):
print('The list contains even number')
break
else:
print('The list does not contain even number')
range()
range() is a built-in function to perform an action a specific
number of times.
range() in Python(3.x) is a renamed version of a function
xrange() in Python(2.x).
It is used to generate a sequence of numbers.
range() takes three arguments.
Start – value to begin the series of numbers; by default
start at 0 [optional]
Stop – value to stop the series; it terminates at n-1 value
Step – value to increment of series [optional]
range()
Example Scripts