Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 05

Python Control Statements

8 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Control statements decide which code runs and how many times.

This chapter covers if else, for and while loops, break, continue, pass and the differences between them.

Real programs choose, repeat and stop.

Control statements are used in almost every exam program.

Menus, validation, searching data, retry logic, games, report generation.

1

Python If else

The if statement runs a block only when its condition is true. elif adds more conditions and else runs when none of the earlier conditions matched. Only one block of an if-elif-else chain executes.

In short: If something is true, do this. Otherwise, do that.

If → elif → else (only one path runs)

Think about it

Decision making is the core of every program, from login checks to grade calculators. An ATM checks: if PIN is correct and balance is enough, dispense cash; else show an error.

Syntax

if condition: block
optional elif condition: block (any number)
optional else: block.

Conditions are tested from top to bottom; the first true one runs and the rest are skipped.

Indentation defines each block.

Conditions can use comparison, logical, membership and identity operators, and chained comparisons like 0 <= x <= 100.

Any value works as a condition through truthiness: if items: is true when the list is not empty.

Nested if

an if inside another if.

Ternary expression

result = a if cond else b.

Separate if statements are all checked; an elif chain is checked only until one succeeds.

Python 3.10+ has match-case for pattern matching.

Common mistakes

  • 1using = instead of ==
  • 2forgetting the colon
  • 3wrong indentation
  • 4checking a broad condition before a narrow one (check marks >= 90 before marks >= 50).

Key points

  • Condition: Expression that is evaluated as true or false.
  • elif: Else-if; checked only if earlier conditions failed.
  • else: Runs when no condition above was true.
  • Nested if: An if statement inside another if block.
  • Ternary expression: One-line if-else that returns a value.
  • End each header (if, elif, else) with a colon.
  • Use == to compare, = to assign.
  • Put the most specific condition first.
  • In an if-elif-else chain only one block runs.

Example

Code
grade, even/odd, nested and ternary:
marks = 78
if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "Fail"
print("Grade:", grade)          # Grade: A

# even or odd
n = 17
if n % 2 == 0:
    print("even")
else:
    print("odd")                # odd

# nested if + logical operator
age, has_id = 20, True
if age >= 18:
    if has_id:
        print("entry allowed")
if age >= 18 and has_id:
    print("same result")

# truthiness and ternary
cart = []
if not cart:
    print("cart is empty")
status = "pass" if marks >= 40 else "fail"
print(status)

# separate ifs all run
x = 10
if x > 5: print("> 5")
if x > 8: print("> 8")
2

Python For Loop

A for loop repeats a block once for every item of an iterable such as a list, tuple, string, dictionary, set or range. The loop variable takes the next item in each round.

In short: For each item in a collection, do something. The loop ends after the last item.

For loop: take each item one by one

Think about it

for is the safest way to process every item because Python manages the counter for you. A grading script loops over all students and prints each result.

Syntax

for item in iterable: block.

range(stop) gives 0..

stop-1; range(start, stop) gives start..

stop-1; range(start, stop, step) moves by step (negative step counts down).

The stop value is never included.

enumerate(seq, start=1) gives index and value; zip(a, b) loops over two sequences together; dict loops use .

items(), .

keys(), .

values().

Nested for loops make patterns and tables.

The optional else block of a for loop runs when the loop finishes without break.

The loop variable is still available after the loop.

Do not add or remove items of a list while looping over it; loop over a copy instead (for x in items[:]).

Use a list comprehension for short transformations: [x * x for x in range(5)].

Time cost is proportional to the number of items.

Key points

  • Iterable: Object you can loop over, like list, str, range, dict.
  • range(): Generates a sequence of integers lazily.
  • enumerate(): Gives (index, item) pairs.
  • zip(): Pairs items from several iterables.
  • Nested loop: A loop inside another loop.
  • range(5) gives 0,1,2,3,4 — the stop value is excluded.
  • Use enumerate() instead of range(len(x)).
  • Looping over a dict gives keys by default.
  • The else of for runs only if there was no break.

Example

Code
range, enumerate, zip, tables, patterns:
for i in range(5):
    print(i, end=" ")                    # 0 1 2 3 4
print()
print(list(range(2, 11, 3)))             # [2, 5, 8]
print(list(range(5, 0, -1)))             # [5, 4, 3, 2, 1]

for ch in "Hi!":
    print(ch)

fruits = ["apple", "banana", "kiwi"]
for idx, name in enumerate(fruits, start=1):
    print(idx, name)

names, scores = ["Ana", "Raj"], [88, 92]
for n, s in zip(names, scores):
    print(f"{n}: {s}")

stock = {"pen": 10, "book": 4}
for item, qty in stock.items():
    print(item, qty)

# multiplication table
for i in range(1, 6):
    print(f"7 x {i} = {7 * i}")

# nested loop: right triangle
for row in range(1, 5):
    print("*" * row)

# sum of 1..100
total = 0
for n in range(1, 101):
    total += n
print(total)                             # 5050

# for-else: search
for n in [3, 5, 7]:
    if n % 2 == 0:
        print("found even")
        break
else:
    print("no even number")              # runs
3

Python While Loop

A while loop repeats a block as long as its condition stays true. The condition is checked before every round. If it is false at the start, the body never runs.

In short: Keep doing this while the condition is true. Stop when it becomes false.

While loop: check → body → update → check again

Think about it

When you do not know how many times to repeat, while is the right tool. A game runs while the player still has lives; a downloader retries while the connection fails.

Syntax

while condition: block.

You must change something inside the loop that eventually makes the condition false; otherwise you get an infinite loop (stop it with Ctrl+C).

Typical uses

the number of rounds is not known in advance, such as reading input until valid, retrying a task, or processing digits of a number.

while True with a break is the standard pattern for menus and validation.

Python has no do-while loop; emulate it with while True and a break at the end.

A while loop can also have an else block, which runs when the condition becomes false normally (not after break).

Pattern for counters

initialise → test → body → update.

Examples

sum of digits (n % 10, n //= 10), factorial, Fibonacci series, and Collatz sequence.

Make sure continue does not skip the update line.

Key points

  • Counter: Variable that tracks the number of rounds.
  • Infinite loop: Loop whose condition never becomes false.
  • Sentinel value: Special value that signals the loop to stop.
  • Loop else: else block that runs when there was no break.
  • Always update the variable used in the condition.
  • while True needs a break inside.
  • Python has no do-while; use while True + break.
  • Ctrl+C stops an infinite loop in a terminal.

Example

Code
countdown, digits, factorial, Fibonacci:
# countdown
n = 5
while n > 0:
    print(n, end=" ")
    n -= 1
print("Go!")                     # 5 4 3 2 1 Go!

# sum of digits
num, total = 4821, 0
while num > 0:
    total += num % 10
    num //= 10
print(total)                     # 15

# factorial
f, k = 1, 5
while k > 1:
    f *= k
    k -= 1
print(f)                         # 120

# fibonacci: first 8 terms
a, b, count = 0, 1, 0
while count < 8:
    print(a, end=" ")
    a, b = b, a + b
    count += 1
print()                          # 0 1 1 2 3 5 8 13

# do-while style input validation
attempts = ["abc", "-4", "25"]    # pretend user inputs
i = 0
while True:
    value = attempts[i]
    i += 1
    if value.isdigit():
        break
    print("invalid:", value)
print("accepted", int(value))     # accepted 25

# while-else
x = 3
while x < 6:
    x += 1
else:
    print("loop ended normally, x =", x)
4

Python Continue

The continue statement skips the rest of the current loop iteration and jumps straight to the next iteration. The loop itself does not stop.

In short: continue means "skip this one and go to the next".

break vs continue vs pass

Think about it

continue keeps loop bodies flat and readable when many items must be skipped. While reading a file, skip empty lines and comment lines, and process the rest.

In a for loop, continue moves to the next item.

In a while loop, it jumps back to the condition check, so make sure the update statement runs BEFORE continue, otherwise the loop may never end.

It only affects the innermost loop.

It is used to ignore unwanted values: blanks, negatives, invalid records, or odd numbers.

Compare with an if-else: continue can reduce nesting by handling the bad case early (a guard clause).

Inside try with finally, the finally block still runs on continue.

Do not confuse continue (next iteration) with pass (do nothing and carry on with the same iteration) and break (leave the loop).

Key points

  • Iteration: One round of a loop.
  • Guard clause: Early skip or exit that avoids deep nesting.
  • Innermost loop: The nearest loop that contains the statement.
  • continue skips only the current iteration.
  • In while loops, update the counter before continue.
  • It affects only the nearest enclosing loop.

Example

Code
skipping unwanted items:
# print odd numbers only
for n in range(1, 11):
    if n % 2 == 0:
        continue
    print(n, end=" ")            # 1 3 5 7 9
print()

# skip blank and comment lines
lines = ["name=Ana", "", "# comment", "age=21"]
for line in lines:
    if not line or line.startswith("#"):
        continue
    print("process:", line)

# while + continue (update BEFORE continue)
i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i, end=" ")            # 1 2 4 5 6
print()

# skip negatives when summing
total = 0
for x in [5, -2, 8, -1, 4]:
    if x < 0:
        continue
    total += x
print(total)                     # 17
5

Python Break

The break statement immediately terminates the nearest enclosing for or while loop. Execution continues with the first statement after the loop. The loop-else block is skipped when break runs.

In short: break means "stop the loop right now".

Think about it

break avoids useless work and is needed for sentinel-controlled loops. A search stops at the first matching record instead of reading the whole database.

break is used when the goal is reached: first match found, correct password entered, or an exit option chosen.

It works only in loops; using it outside a loop is a SyntaxError.

In nested loops it exits only the inner loop.

To leave several loops, use a flag variable, put the loops in a function and return, or raise an exception.

A loop-else runs only if the loop did NOT break, which makes search code neat: for ...

break ...

else "not found".

while True loops almost always have a break.

With try/finally, the finally block still runs.

Breaking early saves time on large data because the remaining items are not processed.

Key points

  • Early exit: Leaving a loop before it would normally end.
  • Flag: Boolean variable used to signal an event, like found.
  • Loop else: Runs only if the loop finishes without break.
  • break exits only the innermost loop.
  • else of a loop is skipped when break happens.
  • break outside a loop is a SyntaxError.

Example

Code
break, for-else and nested exit:
# stop at the first multiple of 7
for n in range(1, 50):
    if n % 7 == 0:
        print("first multiple:", n)   # 7
        break

# search with for-else
names = ["Ana", "Raj", "Lia"]
target = "Raj"
for name in names:
    if name == target:
        print("found")
        break
else:
    print("not found")

# menu loop with break
commands = ["add", "list", "quit", "add"]
for cmd in commands:
    if cmd == "quit":
        print("bye")
        break
    print("running", cmd)

# breaking nested loops with a flag
found = False
for i in range(3):
    for j in range(3):
        if i * j == 2:
            found = True
            break
    if found:
        break
print(i, j)                           # 1 2
6

Python Pass

The pass statement is a null operation. It does nothing when it runs and is used where Python needs a statement but you do not want any action yet.

In short: pass means "do nothing here". It keeps the code valid until you write the real code.

Think about it

pass lets you outline a program first and fill in the details later without syntax errors. A team creates all function names with pass first, then each developer fills in the bodies.

Python does not allow an empty block, so def f(): with no body is a SyntaxError.

Writing pass makes the code valid.

Common uses: (1) stub function or class during design: def todo(): pass; (2) empty class such as a custom exception: class AppError(Exception): pass; (3) an except block that intentionally ignores an error (use carefully and prefer logging); (4) placeholder inside if or loop branches.

pass is different from continue (jumps to next iteration) and break (exits loop).

After pass, execution simply goes to the next statement.

In place of pass you may write ...

(Ellipsis) or a docstring.

Leaving pass in finished code usually means unfinished work.

Key points

  • Null statement: Statement that performs no action.
  • Stub: Empty placeholder function or class.
  • Ellipsis: ... is another way to mark an empty body.
  • pass does nothing; the program continues normally.
  • An empty block without pass is a SyntaxError.
  • pass is not the same as continue or break.

Example

Code
stubs and empty blocks:
def calculate_tax(amount):
    pass                    # to be written later

class AppError(Exception):
    pass                    # empty custom exception

for n in range(5):
    if n == 2:
        pass                # nothing special, but block must exist
    else:
        print(n, end=" ")   # 0 1 3 4
print()

try:
    int("abc")
except ValueError:
    pass                    # ignore error (use with care)

print(calculate_tax(100))   # None (function has no return)
7

Difference between Break and Continue in Python

break terminates the whole loop and moves to the code after the loop. continue only skips the remaining part of the current iteration and moves on to the next iteration of the same loop.

In short: break stops the loop completely. continue skips just this round and keeps looping.

Compare two ideas side by side

Think about it

This pair is one of the most repeated viva and output questions in Python. Processing orders: continue skips cancelled orders; break stops at the first order that fails payment.

Effect: break → loop ends; continue → loop goes on.

After the statement: break resumes after the loop; continue returns to the loop header (next item for for, condition check for while).

Loop-else: break skips the else; continue does not stop the else from running.

Use case: break when you found what you needed; continue when you want to ignore specific items.

Risk

Both work only inside loops and affect only the innermost loop.

Output test: for i in range(1, 6): if i == 3: break → prints 1 2; with continue → prints 1 2 4 5.

Key points

Example

Code
break vs continue side by side:
print("with break:")
for i in range(1, 6):
    if i == 3:
        break
    print(i, end=" ")          # 1 2
print()

print("with continue:")
for i in range(1, 6):
    if i == 3:
        continue
    print(i, end=" ")          # 1 2 4 5
print()

# else behaviour
for i in range(3):
    if i == 1:
        break
else:
    print("else after break?")      # NOT printed

for i in range(3):
    if i == 1:
        continue
else:
    print("else after continue")    # printed

Purpose

break ends the loop.

continue skips one iteration.

Control moves to

break: first statement after the loop.

continue: next iteration of the loop.

Loop else

break prevents else from running.

continue does not.

Typical use

break: search found, exit option.

continue: ignore invalid or unwanted items.

Common risk

break: stopping too early.

continue: skipping the counter update in while loops.

8

Difference Between For Loop and While Loop in Python

A for loop iterates over a known sequence of items and stops when the items are finished. A while loop repeats as long as a condition is true and is used when the number of repetitions is not known in advance.

In short: Use for when you know what to loop over. Use while when you loop until something happens.

Think about it

Choosing the right loop makes the code shorter, safer and easier to read. A report loops with for over all employees; a login screen loops with while until the password is right.

Iteration control: for → driven by an iterable (list, string, range); while → driven by a condition.

Counter: for manages the loop variable automatically; while needs you to initialise and update it.

Risk of infinite loop: low with for (iterables end), high with while if you forget the update.

Typical uses

  • 1for → process every item, fixed counts, tables
  • 2while → input validation, retries, games, digit processing, algorithms like binary search and Euclid GCD

Syntax size: for is shorter for sequences.

Both support break, continue and an else block.

Anything written with for can be written with while and vice versa, but choose the clearer one.

Rule

known items or count → for; unknown count or event-based stop → while.

Key points

  • Definite iteration: Number of repeats is known (for).
  • Indefinite iteration: Repeats until a condition changes (while).
  • Iterable: Object that can be looped over.
  • for = definite iteration; while = indefinite iteration.
  • while needs an initial value and an update statement.
  • Both support break, continue and else.
  • Prefer for for sequences; it avoids counter bugs.

Example

Code
for and while doing the same and different jobs:
# same job: print 1 to 5
for i in range(1, 6):
    print(i, end=" ")
print()

i = 1
while i <= 5:
    print(i, end=" ")
    i += 1
print()

# for is natural for collections
for name in ["Ana", "Raj"]:
    print(name.upper())

# while is natural for unknown repeats: GCD by Euclid
a, b = 48, 18
while b != 0:
    a, b = b, a % b
print("GCD:", a)                  # 6

# halving until 1 (unknown number of rounds)
n, steps = 100, 0
while n > 1:
    n //= 2
    steps += 1
print(steps)                      # 6

Based on

for: an iterable or range.

while: a Boolean condition.

Counter handling

for: automatic.

while: manual initialise and update.

Infinite loop risk

for: very low.

while: high if update is missed.

Best used when

for: count or items known.

while: count unknown, wait for an event.

Code length

for: shorter for collections.

while: longer but more flexible.

Solved examples

Example 01 · Basic

Write a program to check whether a number is positive, negative or zero.

Given Data:
    Required To Find:

    Correct message for any number

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Test n > 0 first
    Step 2: Then n < 0
    Step 3: else the number must be zero
    Final Answer: n = -4 if n > 0: print("positive") elif n < 0: print("negative") else: print("zero") # negative

    Approach note: Order the branches so that each one is clear and non-overlapping.

    Example 02 · Intermediate

    Print the multiplication table of 9 up to 10 using a for loop.

    Given Data:
      Required To Find:

      9 x 1 = 9 ... 9 x 10 = 90

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Use range(1, 11) because stop is excluded
      Step 2: Print f"9 x {i} = {9 * i}"
      Final Answer: for i in range(1, 11): print(f"9 x {i} = {9 * i}")

      Approach note: To include 10 you must write range(1, 11).

      Example 03 · Intermediate

      Print numbers from 1 to 10, skip multiples of 3 and stop completely when the number is 8.

      Given Data:
        Required To Find:

        Output: 1 2 4 5 7

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: If n % 3 == 0: continue
        Step 2: If n == 8: break
        Step 3: Otherwise print n
        Final Answer: for n in range(1, 11): if n % 3 == 0: continue if n == 8: break print(n, end=" ") # 1 2 4 5 7

        Approach note: The order of the two ifs matters only when a number could satisfy both.

        Example 04 · Advanced

        Check whether 37 is prime using a for-else loop.

        Given Data:
          Required To Find:

          Prime or composite

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Loop d from 2 to int(n ** 0.5)
          Step 2: If n % d == 0 print composite and break
          Step 3: else clause means no divisor found: prime
          Final Answer: n = 37 if n < 2: print("not prime") else: for d in range(2, int(n ** 0.5) + 1): if n % d == 0: print("composite") break else: print("prime") # prime

          Approach note: Only test divisors up to the square root of n.

          Real-world applications

          Python

          Using Python Control Statements in real projects

          Menus, validation, searching data, retry logic, games, report generation.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: range(10) includes 10.

          Why this is wrong: The stop value is exclusive.

          ✅ Verified Truth: range(10) gives 0 to 9.

          ⚠️ Exam Tip: Use range(1, 11) to get 1 to 10.

          ❌ Myth: continue stops the loop.

          Why this is wrong: continue only skips the current iteration.

          ✅ Verified Truth: break stops the loop.

          ⚠️ Exam Tip: State the difference in one line.

          ❌ Myth: pass and continue are the same.

          Why this is wrong: pass does nothing and the rest of the iteration still runs; continue jumps to the next iteration.

          ✅ Verified Truth: pass is a placeholder; continue is flow control.

          ⚠️ Exam Tip: Show a print() after pass to prove it.

          ❌ Myth: The else of a loop runs when the loop fails.

          Why this is wrong: It runs when the loop ends without break.

          ✅ Verified Truth: break skips the else block.

          ⚠️ Exam Tip: Use for-else for "not found" logic.

          Revision notes

          Control statements decide which code runs and how many times. This chapter covers if else, for and while loops, break, continue, pass and the differences between them.

          High-Yield Quick Revision Points

          1. if-elif-else: first true condition runs; indent blocks; end headers with a colon.
          2. == compares, = assigns; empty containers, 0 and None are falsy.
          3. for iterates over an iterable; range(stop) excludes stop; use enumerate and zip.
          4. while repeats while the condition is true; always update the condition variable; no do-while in Python.
          5. break exits the nearest loop; continue skips to the next iteration; pass does nothing.
          6. Loop-else runs only when the loop finishes without break.
          7. break vs continue: stop loop vs skip one round.
          8. for vs while: known items/count vs unknown count or event-based stop.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What does list(range(2, 10, 3)) give?

          Question 2 · MCQ (Interview / semester)

          Which statement skips only the current iteration?

          Question 3 · MCQ (Interview / semester)

          What is printed? for i in range(1, 6): if i == 3: break; print(i, end=" ")

          Question 4 · MCQ (Interview / semester)

          Which statement does nothing and acts as a placeholder?

          Question 5 · MCQ (Interview / semester)

          When does the else block of a while loop run?

          Question 6 · MCQ (Interview / semester)

          Which loop is best when the number of repetitions is unknown?

          Question 7 · MCQ (Interview / semester)

          How many times does the body run? i = 0; while i < 3: i += 1

          Question 8 · MCQ (Interview / semester)

          In an if-elif-else chain, how many blocks execute?