←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Control Statements: if, if-else, if-elif-else & Loops (for, while)

Study material and explanations for Unit 2

Control Statements in Python: Conditional & Loop Statements

By default, a Python program executes statements sequentially (line-by-line from top to bottom). Control Statements allow you to change this flow by making decisions, repeating blocks of code, or jumping out of loops.

Classification of Control Statements in Python
1. Conditional (Decision)
if, if-else, if-elif-else, Nested if
2. Looping (Iterative)
for loop, while loop
3. Jump (Transfer)
break, continue, pass

Important Rule in Python — Indentation: Unlike C, C++, or Java which use curly braces { } to group statements, Python uses indentation (4 spaces) after a colon (:) to define a block of code!


1. Conditional Control Statements (Decision Making)

Conditional statements check a boolean condition (True or False) and execute a specific block of code based on the result.

A. Simple if Statement

Executes a block of code only if the given condition is True. If the condition is False, the block is skipped.

age = 20

if age >= 18:
    print("You are eligible to vote!")
print("Program ended.")

B. if-else Statement

Provides two paths: if the condition is True, the if block runs; otherwise (False), the else block runs.

num = int(input("Enter a number: "))

if num % 2 == 0:
    print(f"{num} is an Even number.")
else:
    print(f"{num} is an Odd number.")

C. if-elif-else Ladder

Used when you need to check multiple conditions one after another. In Python, else if is written as elif. As soon as one condition evaluates to True, its block executes and the rest of the ladder is skipped.

Execution Flow of if-elif-else
Check Condition 1 (if)
→ False →
Check Condition 2 (elif)
→ False →
Execute Default (else)
marks = 78

if marks >= 85:
    print("Grade: A+ (Distinction)")
elif marks >= 70:
    print("Grade: A (First Division)")
elif marks >= 50:
    print("Grade: B (Second Division)")
elif marks >= 35:
    print("Grade: C (Pass)")
else:
    print("Result: Fail")

D. Nested if Statement

Writing an if or if-else statement inside another if statement is called a Nested if.

a, b, c = 25, 40, 15

if a > b:
    if a > c:
        print("a is greatest")
    else:
        print("c is greatest")
else:
    if b > c:
        print("b is greatest")
    else:
        print("c is greatest")

2. Loop Control Statements (Iteration)

Loops are used to execute a block of statements repeatedly until a condition is met or a sequence finishes.

A. The for Loop

In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, set, dictionary, or range()).

Syntax:

for variable in sequence:
    # body of loop

Role of the range() Function:

range(start, stop, step) generates a sequence of integers:

  • range(5) → 0, 1, 2, 3, 4 (starts at 0, stops before 5)
  • range(1, 6) → 1, 2, 3, 4, 5
  • range(2, 11, 2) → 2, 4, 6, 8, 10 (step of 2)

Example — Print Multiplication Table of 5:

for i in range(1, 11):
    print(f"5 x {i} = {5 * i}")

Example — Iterate Over a String or List:

fruits = ["Apple", "Mango", "Banana"]
for fruit in fruits:
    print("I like", fruit)

B. The while Loop

The while loop repeats a block of code as long as a boolean condition remains True. It is used when we do not know in advance how many times the loop will run.

Syntax:

while condition:
    # statements
    # update counter variable

Example — Sum of Digits of a Number:

num = 1234
total = 0

while num > 0:
    digit = num % 10
    total += digit
    num = num // 10

print("Sum of digits =", total)  # Output: 10
Feature for Loop while Loop
When to use When the number of iterations is known (iterating over a sequence) When the number of iterations is unknown (depends on a condition)
Syntax for item in sequence: while condition:
Infinite Loop Risk Very low (stops when sequence ends) High if the loop variable is not updated inside the loop

3. Jump / Loop Control Keywords (break, continue, pass)

  1. break Statement: Immediately terminates the loop and transfers control outside the loop.
  2. continue Statement: Skips the remaining statements of the current iteration and jumps to the next iteration of the loop.
  3. pass Statement: A null (empty) statement in Python. Used as a placeholder when syntax requires a block of code, but you don’t want to write anything yet.
for i in range(1, 7):
    if i == 3:
        continue   # Skips printing 3
    if i == 6:
        break      # Stops the loop completely when i reaches 6
    print(i, end=" ")

# Output: 1 2 4 5
# Using pass as a placeholder
def future_function():
    pass  # Prevents IndentationError while leaving the function empty