Unit – 2 Python Programming
Flow of the Control and Conditions
The flow of control in python means the order in which instructions are executed.
There are 3 ways statement can be executed:
i) Sequential statements: lines of code executed one after the other, in order.
ii) Selective statements (Conditional statement): allows to make decision and
execute different code blocks based on conditions. (Using if statements)
iii) Iterative statements (looping statements): executes block of code repeatedly
until a certain condition is met or a specific number of times, using loops
(for/while).
Types of decision-making statements in Python:
1. if statement → runs a block only if condition is True.
2. if-else statement → runs one block if condition is True, another if False.
3. elif statement → checks multiple conditions one after another.
How IF works:
Condition is tested.
If True, the indented code runs.
If False, that code is skipped.
Key points:
No limit to how many statements can be inside an if.
if ends with a colon (:)
Indentation is important – only indented code runs when the condition is
true.
Example given:
Age = int(input("Enter age of a person:"))
if Age >= 18:
print("He is eligible to cast vote")
print("He is not eligible to cast vote")
How If-else statement works:
if checks a condition:
If True, runs the indented block after if.
If False, runs the indented block after else.
Key Points:
No limit on the number of statements in if or else.
if and else must end with a colon (:).
Indentation is important.
Example:
Age = int(input("Enter age of a person:"))
if Age >= 18:
print("He is eligible to cast the vote")
else:
print("He is not eligible to cast the vote")
If age ≥ 18 → eligible, else → not eligible.
How If-elif-else statement works:
Used when there are multiple conditions to check.
Checks conditions one by one:
If one condition is True, its block runs.
If none are true, the else block runs.
Structure:
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
Example use: grading system (if marks ≥ 90 → A, elif ≥ 75 → B, else → C).
Nested if statement:
A nested if is an if that has another if in its if’s body. We can have many levels of
nesting inside the if statement.
if condition:
statemet(s)
if condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
How Nested if statement works:
First the condition is evaluated.
If the result of the condition is true then the block of indented instructions is
performed.
Then the condition with nested if statement is checked and if it is found true
then block of instructions indented under nested if is executed.
If none of this condition is true, then the condition with elif statement is
checked and if found true the statement (s) indented under that are executed.
If none these condition in the ladder of if and elif are true, then the final else
statement will be executed.
Key point:
Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting.
Example:
num=int(input(“Enter a number:”))
if num>=0:
if num==0:
print(“Zero”)
else:
print(“A Positive number”)
else:
print(“A Negative number”)
Iteration statement/Loops:
A looping statement allows a set of instructions to be performed repeatedly until a
certain condition is fulfilled.
Three types of Loops:
While
For
Nested
While loop:
A loop that executes as long as the given condition is true. When the condition
becomes false, the loop stops.
→ It is a conditional and pre-test loop (condition checked before execution).
Key Points:
Loop variable must be initialized before entering the loop.
Condition/test expression decides if the loop body runs.
Statements inside the loop body execute repeatedly while condition is true.
The update expression changes the loop variable inside the loop.
while is a reserved word.
Body may have one or more statements.
Finite loop ends when condition becomes false.
Example (Finite loop):
a=5
while a > 0:
print(a)
a -= 1
print('end')
Output:
5 4 3 2 1 end
Infinite loop: Occurs if condition always stays true and update is missing.
Example:
a=5
while a > 0:
print(a)
print('end') # never reached
Nested While Loop:
A loop inside a loop is called a nested loop. Once the condition of the outer loop is
true, the control is transferred to the inner loop, first the inner loop is terminated
and then the outer loop terminates. The loop control variable for the inner and
outer loop should be different.
Example:
row = 1
while row <= 3: # Inner loop controls the number of asterisks in each row
col = 1
while col <= row:
print("*", end="")
col += 1
print() # Move to the next line after each row
row += 1
Output:
*
**
***
Jump statements: BREAK and CONTINUE
Break and Continue are statement used within loops to alter the normal flow of the
loop’s execution.
Break statement:
This statement is used to force an immediate exit from the loop in which it is
present.
Once the break statement is encountered, the loop terminates and controls jumps to
the statement following the loop.
Execution resumes at the statement immediately after the body of the terminated
statement. A break statement inside a nested loop terminates the inner most loop.
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
Output:
apple ..
Continue statement is used to terminate the current iteration, the loop continues
with the rest of the iterations without ending the loop.
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Output:
apple
cherry
For Loop:
Repeats a block of code for a fixed number of times.
Unlike while, the number of iterations is known (depends on
range/sequence).
Works with numbers, strings, lists, etc.
Each iteration picks the next value in the sequence until it ends.
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
apple
banana
cherry
Key points:
For loop ends when the loop is repeated for the last value of the sequence.
The for loop repeats n number of times, where n is the length of sequence
given in for loop’s header.
Loop variable is a variable that takes a new value from the range each time
loop is executed.
‘else’ statement will be executed after all the iteration of the for loop, if
given.
Else statement of the For loop:
A for loop can have an optional else block as well. The else part is executed if the
items in a sequence used in the for loop exhausts.
Example:
digit = [0,1,5]
for i in digit:
print(i)
else:
print(“No items left”)
Range ( ) function:
Generates a sequence of numbers.
Syntax: range(start, stop, step)
start → beginning value (default = 0)
stop → ending value (excluded)
step → increment (default = 1)
Often converted to a list using list(range(...)).
Examples
list(range(10)) # [0,1,2,3,4,5,6,7,8,9]
list(range(2, 7)) # [2,3,4,5,6]
list(range(2, 20, 3)) # [2,5,8,11,14,17]
Operators in and not in
Test if a value exists in a sequence (list, string, tuple, etc.).
Return True if found, else False.
Examples
4 in [1,2,3,4] # True
'a' in "number" # False
"num" in "number" # True
4 not in [1,2,3,4] # False
'a' not in "number" # True
"num" not in "number" # False