Unit Ii
Unit Ii
Unit Ii
Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
python, For loop using ranges, string, list and dictionaries. Use of while loops in python, Loop
manipulation using pass, continue, break and else. Programming using Python conditional
and loop blocks.
In Python, flow control allows you to determine the order in which statements or code blocks
execute at runtime based on conditions. Let’s explore the key concepts:
Iterative Statements (Loops): These allow you to repeat a block of code as long as a condition
remains true.
Two common loop statements:
• for loop: Iterates over a sequence (e.g., a list, range, or string).
• while loop: Repeats as long as a specified condition holds true.
In Python, the if statement is used for conditional execution. It allows you to execute a block
of code only when a specific condition is met. Here’s how it works:
Python if Statement
An if statement executes a block of code only if the specified condition is met.
Syntax
if condition:
# body of if statement
Here, the spaces before the print() statement denote that it's the body of the if statement.
number = 10
output:
Number is positive
This statement always executes
if...else Statement
An if statement can have an optional else clause. The else statement executes if the condition
in the if statement evaluates to False.
Syntax
if condition:
# body of if statement
else:
# body of else statement
if number > 0:
print('Positive number')
else:
print('Negative number')
Output:
Positive number
This statement always executes
if…elif…else Statement
The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, we use
the if...elif...else statement.
Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Here,
• if condition1 - This checks if condition1 is True. If it is, the program executes code
block 1.
if number > 0:
print('Positive number')
else:
print('Zero')
Output
Zero
This statement is always executed
for Loop
In Python, a for loop is used to iterate over sequences such as lists, strings, tuples, etc.
languages = ['Swift', 'Python', 'Go']
Output
In the above example, we have created a list called languages. As the list has 3 elements, the
loop iterates 3 times.
The value of i is
• Swift in the first iteration.
• Python in the second iteration.
Here, val accesses each item of the sequence on each iteration. The loop continues until we
reach the last item in the sequence.
Flowchart of Python for Loop
P
y
values = range(4)
0
1
2
3
Output:
b
a
n
a
n
a
Output:
apple
banana
cherry
Output
Enter a number: 3
Enter a number: 2
Enter a number: 1
Enter a number: -4
Enter a number: 0
The sum is 2