Control Flow in Python

Control flow allows you to control the execution of your program based on conditions and repetition.

💡 Control flow decides what runs, when it runs, and how many times.

if Statement

The if statement runs code only when a condition is true.

age = 18

if age >= 18:
    print("You are eligible to vote")

if – else

age = 15

if age >= 18:
    print("Adult")
else:
    print("Minor")

if – elif – else

marks = 75

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

Loops in Python

Loops allow you to repeat code multiple times.

🔁 Python has two main loops: for and while.

for Loop

Used when you know how many times you want to loop.

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

Looping Through a List

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)

while Loop

Runs as long as the condition remains true.

count = 1

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

break Statement

Stops the loop immediately.

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

continue Statement

Skips the current iteration.

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

Practice Exercises

  1. Check if a number is even or odd
  2. Print numbers from 1 to 20 using a loop
  3. Print only even numbers using continue
  4. Stop the loop when number reaches 10