Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Control Structures in Python

This document covers control structures in Python programming, including selection statements like if, if-else, and nested if, as well as iterative statements such as while and for loops. It explains the syntax and flow control for these statements, provides examples, and discusses the use of break, continue, and pass statements. Additionally, it includes practice exercises to reinforce the concepts presented.

Uploaded by

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

Control Structures in Python

This document covers control structures in Python programming, including selection statements like if, if-else, and nested if, as well as iterative statements such as while and for loops. It explains the syntax and flow control for these statements, provides examples, and discusses the use of break, continue, and pass statements. Additionally, it includes practice exercises to reinforce the concepts presented.

Uploaded by

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

Python Programming

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

if(num1 > num2)


big = num1
if else statement
 It will check the given condition, if it is true then take
action-1 otherwise take action-2
 Syntax
if(condition) :
suite1_statement(s)
else :
suite2_statements(s)
 Flow Control
False True
if(condition)

suite1 Suite2
statement(s) statement(s)
if else statement
 Examples

if(num1 > num2) :


big = num1
print(‘Biggest Number = ‘, big)
else :
big = num2
print(‘Biggest Number = ‘, big)
Nested if else statement
 It will check the compound conditions, based on that it
will execute suite statements(s).
 Syntax
if(condition-1) :
if(condition-2) :
suite1_statements(s)
else :
suite2_statements(s)
else :
if(condition3) :
suite3_statements(s)
else :
suite4_statements(s)
Nested if else statement
 Flow Control

False True
if(cond-1)

False True False True


if(cond-3) if(cond-2)

Suite4 Suite3 Suite1 Suite2


statement(s) statement(s) statement(s) statement(s)
Nested if else statement
 Example

if(num1 > num2) :


if(num1 > num3) :
big = num1
else :
big = num3
else :
if(num2 > num3) :
big = num2
else :
big = num3
if elif statement
 It will check the cond-1, if it is true then executes
suite1_stmt(s); otherwise check the cond-2, if it is true
then executes suite12_stmt(s), likewise it continue upto
end
 Syntax
if(cond-1) :
suite1_statements(s)
elif(cond-2) :
suite2_statements(s)
elif(cond-3 :
suite3_statements(s)
else
suiteN_statements(s)
if elif statement
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

Nested if..elif (switch logic)


34. WAS to print the given vowel into in to words
35. WAS to print the given digit into in to words (0- 5)
Practice Script Exercises
#PS 30 To convert the character lower case into upper
case
ch = input('Enter a character : ')
if(ch >= 'a' and ch <= 'z') :
lowch = ord(ch) # ch as ASCII
lowch = lowch - 32
lowch = chr(lowch) # ASCII asch
print(lowch)
else :
print(ch)
Practice Script Exercises
#PS 31 To convert the character upper case into lower
case
str = input('Enter a string : ')
lowstr = str.lower()
print(lowstr)
Iterative / Repetitive / Looping
Statements
The iterative statements are used to execute a part of the
script repeatedly as long as a given condition is True.
Python provides the following iterative statements.

 while statement
 for .. in statement
While Statement

 While statement is used to execute a statement or set of


statements repeatedly as long as a given condition is
True.
 It is also known as entry control statement. First it checks
the given condition, depending the condition it executes
the statement(s).
 Syntax
intialize stmt
while(condition) :
suite statement(s)
[else :
suite statement(s)]
Using else Statement with
While Loops
 Python supports else statement associated with a loop
statement.

 If the else statement is used with a while loop,


the else statement is executed when the condition
becomes false.
Flow Control
initialize
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)

 for .. in loops only implements in the collection-based


iteration
Using else Statement with
for .. in Loops
 Python supports an else statement associated with a loop
statement.

 If the else statement is used with a for .. in loop,


the else block is executed only if for .. in loops terminates
normally (and not by encountering break statement).
for .. in Statement
 Syntax
for <variable> in <sequence> :
suite statement(s)
[else :
suite statement(s)]
Flow Control
Process first element in sequence

False
Is
Next If No more elements in sequence
element in
sequence
?
True

Process Next element in sequence

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

Control Statement & Description


break statement
Terminates the loop statement and after the loop.

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

#Prg 44, Prg for traversal of List index, 14/11/2021


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')
range()
 Example Scripts
#Prg 45, Prg to find sum of nos., sum of odd nos., and sum of even nos.
14/11/2021
n = int(input('Enter a the value of n :'))
sum = sumodd = sumeven = 0
for ncnt in range(1, n):
print(ncnt)
sum = sum + ncnt
for ocnt in range(1, n, 2):
print(ocnt)
sumodd = sumodd + ocnt
for ecnt in range(2, n, 2):
print(ecnt)
sumeven = sumeven + ecnt
print("Sum of first 10 numbers : ", sum)
print("Sum of odd number upto 10 : ", sumodd)
print("Sum of even number upto 10 : ", sumeven)
Practice Script Exercises
46. WAS to print the natural number up to n
47. WAS to print odd or even number between 1 to n.
48. WAS to print the sum of numbers up to N
49. WAS to print the sum of odd numbers up to N
50. WAS to print the sum of even numbers up to N
51. WAS to print the factorial of given number N.
Wish You All the Best

You might also like