3. Control Flow Statements

Control flow statements control the execution of a program based on conditions and loops.


Decision Making Statements

1. if Statement

The if statement executes code only if the condition is True.

Syntax

if condition:
# code

Example

age = 18

if age >= 18:
print("You can vote")

Output:

You can vote

2. if...else Statement

Used when there are two possible outcomes.

Syntax

if condition:
# code if true
else:
# code if false

Example

number = 5

if number % 2 == 0:
print("Even")
else:
print("Odd")

3. if...elif...else Statement

Used to check multiple conditions.

Syntax

if condition1:
# code
elif condition2:
# code
else:
# code

Example

marks = 75

if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")

Nested Conditions

An if statement inside another if statement is called nested condition.


Example

age = 25
citizen = True

if age >= 18:
if citizen:
print("Eligible to vote")

Loops in Python

Loops are used to repeat code multiple times.

Python has:

  • for loop
  • while loop

1. for Loop

Used to iterate over a sequence.

Syntax

for variable in sequence:
# code

Example 1: Loop through List

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
print(fruit)

Example 2: Loop through String

for ch in "Python":
print(ch)

2. while Loop

Runs as long as condition is True.

Syntax

while condition:
# code

Example

count = 1

while count <= 5:
print(count)
count += 1

Infinite Loop

If condition never becomes false.

while True:
print("Running forever")

Use carefully.


Loop Control Statements

Used to control loop execution.


1. break

Stops the loop immediately.


Example

for i in range(1, 10):
if i == 5:
break
print(i)

Output:

1
2
3
4

2. continue

Skips current iteration and moves to next iteration.


Example

for i in range(1, 6):
if i == 3:
continue
print(i)

Output:

1
2
4
5

3. pass

Does nothing.

Used as placeholder.


Example

for i in range(5):
pass

Range Function

The range() function generates a sequence of numbers.


Syntax

range(start, stop, step)

Parameters:

  • start → starting value
  • stop → ending value (excluded)
  • step → increment/decrement

Example 1: Basic Range

for i in range(5):
print(i)

Output:

0
1
2
3
4

Example 2: Start and Stop

for i in range(2, 6):
print(i)

Output:

2
3
4
5

Example 3: Step Value

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

Output:

1
3
5
7
9

Reverse Loop

for i in range(10, 0, -1):
print(i)

Nested Loops

Loop inside another loop.


Example

for i in range(1, 4):
for j in range(1, 3):
print(i, j)

Practical Examples

Example 1: Sum of Numbers

total = 0

for i in range(1, 6):
total += i

print(total)

Output:

15

Example 2: Multiplication Table

num = 5

for i in range(1, 11):
print(num, "x", i, "=", num * i)