0% found this document useful (0 votes)
79 views

5 Flow Control

Python provides three types of flow control statements: sequence, selection, and iteration. Sequence statements execute code sequentially. Selection statements like if/else execute one block of code or another depending on a condition. Iteration statements like for and while loops repeatedly execute a block of code as long as a condition is true. Python supports conditional if, if/else, and if/elif/else statements. For loops iterate over a sequence, while loops repeat until a condition is no longer true. Nested loops and break/continue statements provide additional control flow capabilities.

Uploaded by

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

5 Flow Control

Python provides three types of flow control statements: sequence, selection, and iteration. Sequence statements execute code sequentially. Selection statements like if/else execute one block of code or another depending on a condition. Iteration statements like for and while loops repeatedly execute a block of code as long as a condition is true. Python supports conditional if, if/else, and if/elif/else statements. For loops iterate over a sequence, while loops repeat until a condition is no longer true. Nested loops and break/continue statements provide additional control flow capabilities.

Uploaded by

Vasantha Peram
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Python

Flow control:
Statement Flow control:
In a program, statements may be executed sequentially, selectively or
iteratively.
Sequence:
The sequence construct means the statements are being executed
sequentially. This represents the default flow of statement.
Selection:
The selection construct means the execution of statements depending upon a
condition-test. If a condition evaluates True, a set of statements is followed
otherwise a different set of statements are executed. This construct is also called
decision construct because it helps in making decision about which set of statements
are executed.
We can apply decision making or selection in your real life so many times e.g., if the
traffic signal light is red, then stop; if the traffic signal light is yellow then wait; and if
the signal is green then go.
Iteration(Looping):
The iteration constructs means repetition of a set of statements depending upon a
condition-test. Till the time a condition is True (or False depending upon the loop), a
set of statements are repeated again and again. As soon as the condition becomes
False. The iteration construct is also called as looping construct.
Flow control

Selective Statements Iterative statements Transfer Statements

if for break
if-else while continue
if-elif-else pass

1
Python

Selection statements or conditional statements:


Simple If-condition
Syntax:
if condition:
Statements
The simplest form of if statement tests a condition evaluates to True, it carries out
some instructions and does nothing in case condition evaluates to false.

Ex:
name=input("Enter name") if
name="Krishna":
print("Hello Krishna!Goodmorning")
print("How r u")

If-else condition
Syntax:
if condition:
Statements
else:
statements
This form of if statement tests a condition and if the condition evaluates to True, it
carries out statements indented below if and in case condition evaluates to false, it
carries out statements indented below else.

Ex:
name=input("Enter name") if
name="rama":
print("Hello rama! Good morning")
else:
print("Hello Guest! How r u")

2
Python

If-elif-else condition
Syntax:
if condition1:
Statements
elif condition2:
statements
elif condition3:
statements

elif condition-n:
statements
else:
statements
Ex:
a=int(input("Enter a number:") if
a==1:
print("Sunday")
elif a==2:
print("Monday")
elif a==3:
print("Tuesday")
elif a==4:
print("Wednesday")
elif a==5:
print("Thursday")
elif a==6:
print("Friday")
elif a==7:
print("Saturday")
else:
print("Invalid no")
3
Python

Ternary operators: -
Syntax:
x=firstvalue if condition else secondvalue
If condition is True then firstvalue will be considered else secondvalue will be
considered.
Ex: To read two numbers and print minimum value
a=int(input("Enter firstno:"))
b=int(input("Enter secondno:"))
min=a if a<b else b
print("Minimum value=",min)

Nesting of ternary operator is possible


Ex: To read three numbers and print maximum value
a=int(input("Enter firstno:"))
b=int(input("Enter secondno:"))
c=int(input("Enter thirdno:"))
max=a if a>b and a>c else b if b>c else c
print("Maximum value=",max)
Ex:
a=int(input("Enter firstno:"))
b=int(input("Enter secondno:"))
print("Both numbers are equal" if a==b else "Firstno is greater than secondno" if a>b
else "Firstno is less than secondno")

4
Python

Iterative statements:
The iteration statements or repetition statements allow a set of instructions to be
performed repeatedly until a certain condition is fulfilled. The iteration statements are
also called loops or looping statements.
Python provides two kinds of loops:
- While loop
- For loop
Actually loops are two categories:
Counting loops: The loops that repeat certain number of times. Python’s for loop is
counting loop.
Conditional loop: The loops that repeat until a certain thing happens i.e, they
keep repeating as long as some condition is true. Python’s while loop is conditional
loop.

While loop:
If we want to execute a group of statements iteratively until some condition false,
then we should go for while loop.
Syntax:
while condition:
statements

Ex: Display natural numbers between 1 to 10


i=1
while i<=10:
print(i)
i=i+1

Ex: Accept names until user enters the choice is stop


n=input("Enter a name:")
while n!="stop":
n=input("Enter a name:(stop to exit):")

5
Python

Ex: The below example represent infinite times.


while(True):
print ("hi Krishna")

Ex:
while True:
eid = input("Enter emp id")
ename=input("enter emp name")
if(ename=="krishna"):
print("login success")
break
else:
print("login fail try with valid name")

Ex: Write a python program to reverse any number.

n=int(input("Enter a Number : "))


rev=0
while(n): r=n
%10
rev=rev*10+r
n=n//10
print(rev)

6
Python

for loop:
If we want to execute some action for every element present in some sequence
(it may be string or collection) then we should go for for loop. Syntax:
for variable in sequence:
statements
 The loop variable is assigned the first value in the sequence.
 All the statements in the body of for loop are executed with assigned value of
loop variable.
Once step 2 is over, the loop variable is assigned the next value in the sequence and
the loop body is executed with the new value of loop variable.
This continues until all values in the sequences are processed.

The range() function:


The range() function of Python is used with the Python for loop. The range() function
of Python generates a list which is a special sequence type. A sequence in Python is a
succession of values bound together by a single name. Some Python sequence types
are: Strings, Lists, Tuples etc.
range(number)  0 to number -1
Ex:

>>>r=range(10)
>>>type(r)
<class ‘range’>
>>>r[0]
0
>>>r[-1]
9
>>>r[2:8]
range(2,8)
>>>for i in r(2:8): print (i)
2
3

7
Python

4
5
6
7
range(begin,end)  begin to end-1
range(10,20)  10 to 19
>>>for i in range(10,20): print(i)
10 11 12 13 14 15 16 17 18 19
range(begin,end,step)  begin to end-1 change by step value
range(1,101,5)  1,6,11,16…..
>>>for i in range(0,101,5): print(i)

Ex:
for i in range(5):
print("Hello:",i)

Ex: Display natural numbers between 1 to 10


for i in range(1,11):
print(i)

Ex: Display odd numbers between 1 to 10


for i in range(1,11,2): print(i)

Ex: Display natural numbers between 10 to 1


for i in range(10,0,-1):
print(i)
Ex:
sum=0
for i in range(1,100):
sum=sum+i
print sum

8
Python

Ex:
for i in range(1,10):
if i%2==0:
print("even number=",i)
else:
print("odd number",i)

Operators in and not in:


To check whether a value is contained inside a list we can use in operator.
Ex:
3 in [1,2,3,4]
#This expression will test if value 3 is contained in the given sequence.
Will return True as value 3 is contained in sequence [1,2,3,4]
5 in [1,2,3,4]
#This expression will test if value 5 is contained in the given sequence.
Will return False as value 5 is not contained in sequence [1,2,3,4]

To check whether a value is not contained inside a list we can use not in
operator.
Ex:
3 not in [1,2,3,4]
#This expression will test if value 3 is not contained in the given sequence.
Will return False as value 3 is contained in sequence [1,2,3,4]
5 not in [1,2,3,4]
#This expression will test if value 5 is not contained in the given sequence.
Will return True as value 5 is not contained in sequence [1,2,3,4]

# Iterating over a List


data l=["krishna", "Govinda]

9
Python

# Iterating over a tuple


t = ("aaa", "bbb", "ccc")
for i in t:
print(i)

# Iterating over a String


s ="krishna"
for i in s :
print(i)

# Iterating over dictionary


d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))

Ex:
words = ["cat", "apple", "one","four"]

for w in words:
print(w, len(w))

Ex:
result4 = [ ]
l=[10,20,30,40]
for x in l:
if x>20:
result4.append(x+1)
print(result4)

10
Python

Nested loops:
Sometimes we can take a loop inside another loop, which are also known as nested
loops.
Ex:
for i in range(4):
for j in range(4):
print("i=",i," j=",j)

Transfer statements:
break: Break can be used to unconditionally jump out of the loop. It terminates the
execution of the loop. Break can be used in while loop and for loop. Break is mostly
required, when because of some external condition, we need to exit from a loop.
Example
for letter in "Python":
if letter = = 'h':
break
print letter

will result into


P
y
t

Ex:
for i in range(10):
if i==7:
print("Processing is enough….")
break
print(i)
print("End of loop")

11
Python

Ex:
a=int(input("Enter any number greater than 10:\t"))
while a>0:
a=a-1
if a==10:
break
else:
print(a,"These are the numbers upto 10")

Ex:
a=b=c=0
for i in range(1,21):
a=int(input("Enter number1: "))
b=int(input("Enter number2: "))
if b==0:
print("Division by zero error")
break
else:
c=a/b
print("Quotient=",c)
print("Program over")

continue: - Within the loop, if you want to current iteration should be skipped and
continue to the next iteration then continue statement is used.
Example
for letter in "Python":
if letter == 'h':
continue
print letter

P
y
12
Python

t
o
n

Ex:
for i in range(10):
if i%2==0:
continue
print(i)
Ex:
a=int(input("Enter any number greater than 10:\t"))
while a>0:
a=a-1
if a==10:
continue
else:
print (a,"These are the numbers upto 10")

Ex: Sum of 10 positive numbers


sum=0
count=0
for i in range(1,11):
s=int(input("Enter a number:")) if
(s<0):
continue
sum+=s
count+=1
print("Sum of elements=",sum)
print("Adding elements count=",count)

Ex:
a=b=c=0
13
Python

for i in range(3):
a=int(input("Enter number1: "))
b=int(input("Enter number2: "))
if b==0:
print("The denominator cannot be zero. Enter again")
continue
else:
c=a/b
print("Quotient=",c)

Ex:
numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print("Cannot divide by zero")
continue
print("100/{} = {}".format(n,100/n)

pass: - In our programming syntactically block is required which we won’t do


anything, then we can define that empty block with pass keyword, otherwise it
displays indentation error.
Ex:
if True:
Error: Unexpected EOF while parsing.
Ex:
if True: pass
No problem, this is empty block
The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action. For example: Case:
while True:
pass

14
Python

Case: This is commonly used for creating minimal classes:


class MyEmptyClass:
pass
Case: Another place pass can be used is as a place-holder for a function or
conditional body when you are working on new code, allowing you to keep
thinking at a more abstract level. The pass is silently ignored.
def initlog(*args):
pass # Remember to implement this!

Loops with else block :


Both loops of Python have an else clause, which is different from else of if- else
statement. The else of a loop executes only when the loop ends normally (i.e., only
when the loop is ending because the while loop’s test condition has resulted in false
or the for loop has executed for the last value in sequence.) Ex: else is always
executed if the loop executed normally termination. for i in range(1, 5):
print(i)
else:
print('The for loop is over')

Ex:
for a in range(1,4):
print("Element is:",a)
else:
print("Ending loop after printing all elements of sequence")

Ex:
for a in range(1,4):
k=int(input("Enter a number:"))
if k%2==0:
break

15
Python

print("Element is:",k)
else:
print("Ending loop after printing all elements of sequence")

Ex: else is always executed after the loop is over unless a break
statement is encountered.
a=0
while(a<10):
print(a)
a=a+1
else:
print("else block after while");
print("process done")

Ex: Prime no or not


n=int(input("Enter a no:"))
for i in range(2,n):
if n%2==0:
print("Not a prime no")
break
else:
print("Prime no")

16

You might also like