flow of control in python – class 11 notes
what is flow of control
- it refers to the order in which individual statements instructions or function calls are executed in
a program
types of control flow
1 sequential flow
2 conditional flow
3 iterative flow
------------------------------------------
1 sequential flow
- default flow where statements execute one after another
example
print("start")
x = 10
print(x * 2)
------------------------------------------
2 conditional flow
python uses
- if
- if else
- if elif else
if statement
syntax
if condition:
# code block
example
age = 18
if age >= 18:
print("eligible to vote")
if else statement
syntax
if condition:
# true block
else:
# false block
example
num = 5
if num % 2 == 0:
print("even")
else:
print("odd")
if elif else ladder
syntax
if condition1:
# block1
elif condition2:
# block2
elif condition3:
# block3
else:
# else block
example
marks = 85
if marks >= 90:
print("grade a")
elif marks >= 75:
print("grade b")
elif marks >= 60:
print("grade c")
else:
print("grade d")
note
- indentation is crucial in python
- conditions must evaluate to a boolean value true or false
------------------------------------------
3 iterative flow
used when we want to execute a block of code repeatedly
python supports
- while loop
- for loop
while loop
syntax
while condition:
# code block
example
i=1
while i <= 5:
print(i)
i += 1
for loop
used to iterate over a sequence like list tuple string or range
syntax
for variable in sequence:
# code block
example
for i in range(1 6):
print(i)
range function
- range(start stop step)
- start → starting value default 0
- stop → ending value exclusive
- step → increment default 1
examples
range(5) → 0 1 2 3 4
range(1 6) → 1 2 3 4 5
range(1 10 2) → 1 3 5 7 9
------------------------------------------
4 loop control statements
break statement
terminates the loop prematurely
example
for i in range(10):
if i == 5:
break
print(i)
continue statement
skips the current iteration and continues with the next one
example
for i in range(5):
if i == 2:
continue
print(i)
pass statement
a null statement used as a placeholder
does nothing but syntactically required
example
for i in range(5):
if i == 3:
pass
print(i)
------------------------------------------
5 nested loops and conditions
you can place one loop or conditional block inside another
example
for i in range(1 4):
for j in range(1 4):
print(i j)
if score >= 90:
if attendance >= 75:
print("excellent")
else:
print("improve attendance")
------------------------------------------
6 infinite loops
a loop that runs endlessly because the condition never becomes false
example
while true:
print("this will run forever")