Python Control Flow Statements – Complete Guide with Real-Life Examples

Python Control Flow Statements – Complete Guide with Real-Life Examples

Published on Code with Py  |  Category: Python Basics  |  Reading time: ~15 min

Control flow statements decide how a program runs, which code executes, and how many times it repeats. In real life, we use control flow every day — "If it rains, take an umbrella. Else, go normally." Python gives you clean and powerful tools to control program logic. In this post, you will learn every major control flow statement with real-life problems, Python solutions, explanations, and practice exercises.

Table of Contents

  1. What is Control Flow?
  2. if Statement
  3. if–else Statement
  4. if–elif–else Ladder
  5. Nested if Statement
  6. for Loop
  7. while Loop
  8. break, continue, and pass
  9. Loop with else
  10. Real-Life Combined Example – ATM System
  11. Practice Problems
  12. FAQ

1. What is Control Flow in Python?

By default, Python executes code line by line from top to bottom. But in real programs, we need to make decisions, repeat actions, and skip certain steps. This is where control flow statements come in.

Control flow statements are divided into three categories:

Decision Making

  • if
  • if–else
  • if–elif–else
  • Nested if

Looping

  • for loop
  • while loop
  • Loop with else

Jump Statements

  • break
  • continue
  • pass

2. if Statement

The if statement is the simplest decision-making tool. It runs a block of code only when a given condition is True.

Syntax:

if condition:
    # code runs only if condition is True
Real-life problem

A student passes an exam only if marks are 40 or above.

marks = 45

if marks >= 40:
    print("Student Passed")
Output: Student Passed
The if block runs only when the condition is True. Since 45 >= 40 is True, the message is printed. If marks were 30, nothing would print.

3. if–else Statement

The if–else statement gives you two paths. If the condition is True, the if block runs. If it is False, the else block runs. Exactly one block always executes.

Real-life problem

Check whether a number is even or odd.

num = 7

if num % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")
Output: Odd Number
7 % 2 gives remainder 1, which is not 0. So the condition is False and the else block runs.

4. if–elif–else Ladder

When you have more than two possible outcomes, you use the elif (else if) ladder. Python checks each condition one by one. As soon as one condition is True, that block runs and the rest are skipped.

Real-life problem

Grade a student based on marks: 90+ → A, 75–89 → B, 50–74 → C, below 50 → Fail.

marks = 82

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")
Output: Grade B
Since marks = 82, the first condition (82 >= 90) is False. The second condition (82 >= 75) is True, so "Grade B" is printed and remaining checks are skipped.

5. Nested if Statement

A nested if is an if statement inside another if statement. You use it when you need to check multiple dependent conditions — only check the inner condition if the outer one is already True.

Real-life problem

A user can vote only if age is 18 or above AND citizenship is Indian.

age = 20
citizen = "Indian"

if age >= 18:
    if citizen == "Indian":
        print("Eligible to vote")
    else:
        print("Not an Indian citizen")
else:
    print("Underage – cannot vote")
Output: Eligible to vote
Nested if can get complex quickly. Keep nesting to a maximum of 2–3 levels. Beyond that, use logical operators like and / or for cleaner code.

6. for Loop

A for loop is used when you know how many times you want to repeat something. It iterates over a sequence such as a range, list, string, or tuple.

Syntax:

for variable in sequence:
    # code to repeat
Example 1

Print numbers from 1 to 5.

for i in range(1, 6):
    print(i)
1
2
3
4
5
Example 2

Print each character of a string.

for char in "Python":
    print(char)
P
y
t
h
o
n
range(1, 6) generates numbers from 1 to 5. The stop value (6) is not included. Use range(start, stop, step) for more control.

7. while Loop

A while loop runs as long as a condition is True. Use it when you do not know in advance how many times the loop will run — it depends on a condition.

Real-life problem

Print numbers from 1 to 5 using a while loop.

i = 1

while i <= 5:
    print(i)
    i += 1
1
2
3
4
5
Always make sure your while loop has a way to become False. If the condition never becomes False, the loop runs forever — this is called an infinite loop and will crash your program.

8. break, continue, and pass

These are called jump statements — they change the normal flow of a loop.

8.1 break – Exit the loop immediately

Problem

Stop printing numbers when the value reaches 5.

for i in range(1, 10):
    if i == 5:
        break
    print(i)
1
2
3
4
When i reaches 5, the break statement immediately exits the loop. Numbers 5 to 9 are never printed.

8.2 continue – Skip the current iteration

Problem

Print all numbers from 1 to 7 but skip number 5.

for i in range(1, 8):
    if i == 5:
        continue
    print(i)
1
2
3
4
6
7
When i == 5, continue skips that iteration and moves to the next. The loop does not stop — it just skips 5.

8.3 pass – Do nothing (placeholder)

for i in range(3):
    pass  # logic will be added later

print("Loop finished")
Loop finished
pass is used when Python requires a statement but you have no logic to write yet. It is a placeholder that does nothing and prevents syntax errors.

9. Loop with else

Python has a unique feature — you can attach an else block to a loop. The else block runs only if the loop completes normally without hitting a break statement.

Real-life problem

Search for a number in a list. Print "Found" if it exists, otherwise print "Not Found".

nums = [2, 4, 6, 8]
target = 5

for n in nums:
    if n == target:
        print("Found")
        break
else:
    print("Not Found")
Not Found
Since 5 is not in the list, break never runs, so the else block executes and prints "Not Found". If 5 were found, break would stop the loop and skip the else block.

10. Real-Life Combined Example – ATM Withdrawal System

This example combines if, nested if, and real-world logic. This type of problem is commonly asked in Python coding interviews and placement tests.

pin = 1234
balance = 5000
entered_pin = 1234
withdraw = 3000

if entered_pin == pin:
    if withdraw <= balance:
        balance -= withdraw
        print("Withdrawal Successful")
        print(f"Remaining Balance: ₹{balance}")
    else:
        print("Insufficient Balance")
else:
    print("Incorrect PIN. Try again.")
Withdrawal Successful
Remaining Balance: ₹2000

11. Practice Problems

The best way to master control flow is by practising. Try solving these problems on your own before looking at any solution.

if / if–else

  • Check if a number is positive
  • Check voting eligibility (age >= 18)
  • Even or odd number
  • Vowel or consonant checker
  • Pass or fail (pass mark = 40)

if–elif–else

  • Grade calculator (A/B/C/Fail)
  • Simple calculator (+, -, *, /)
  • Traffic light logic
  • Largest of 3 numbers
  • Age group classifier

Loops

  • Print 1 to 10 using for
  • Sum of 1 to 100
  • Multiplication table of 5
  • Countdown from 10 to 1
  • Count digits in a number

break / continue / pass

  • Stop loop when sum > 50
  • Skip multiples of 5
  • Search element, stop if found
  • Skip negative numbers in sum
  • Empty function using pass

Real-life projects

  • ATM Withdrawal System
  • Login validation (3 attempts)
  • Online discount calculator
  • Bus ticket booking logic
  • Student attendance checker
How to practise properly: Always try to write the solution yourself first. Test with multiple inputs. Avoid copy-pasting. Understanding the logic matters more than the output.

Quick Summary – What You Learned
  • if runs a block only when a condition is True
  • if–else gives two paths — one always runs
  • elif ladder handles multiple conditions in sequence
  • Nested if checks dependent conditions inside each other
  • for loop is used when iterations are known in advance
  • while loop runs as long as a condition is True
  • break exits the loop, continue skips the iteration, pass does nothing
  • Loop else runs only when the loop completes without break

Frequently Asked Questions (FAQ)

Q1. What is the difference between a for loop and a while loop in Python?

A for loop is used when you know the number of iterations in advance (e.g., looping 10 times). A while loop is used when the number of iterations depends on a condition that may change during execution.

Q2. Can we use else with a for loop in Python?

Yes. Python allows an else block with both for and while loops. The else block runs only if the loop completes normally without a break statement being triggered.

Q3. What is the difference between break and continue?

break exits the entire loop immediately. continue skips the current iteration and moves to the next one. The loop continues running after a continue statement.

Q4. What does pass do in Python?

pass is a null statement. It does nothing when executed. It is used as a placeholder where Python syntax requires a statement but you have no logic to write yet — such as empty functions, classes, or loops.

Q5. What is a nested if statement and when should I use it?

A nested if is an if statement placed inside another if statement. Use it when you need to check a second condition only after the first condition is already True. Avoid nesting more than 2–3 levels deep for code readability.

Q6. How do I avoid an infinite while loop?

Always make sure the loop variable is updated inside the loop body so the condition eventually becomes False. You can also use a break statement as a safety exit inside the loop.


Found this post helpful? Share it with your friends learning Python. Drop your questions or practice solutions in the comments below — happy to review!


Previous       Next



Comments

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Loops Explained – for Loop and while Loop with Examples and Output