Python Control Flow Statements – Complete Guide with Real-Life Examples
Python Control Flow Statements – Complete Guide with Real-Life Examples
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
- What is Control Flow?
- if Statement
- if–else Statement
- if–elif–else Ladder
- Nested if Statement
- for Loop
- while Loop
- break, continue, and pass
- Loop with else
- Real-Life Combined Example – ATM System
- Practice Problems
- 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
A student passes an exam only if marks are 40 or above.
marks = 45 if marks >= 40: print("Student Passed")
Output: Student Passed
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.
Check whether a number is even or odd.
num = 7 if num % 2 == 0: print("Even Number") else: print("Odd Number")
Output: Odd Number
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.
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
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.
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
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
Print numbers from 1 to 5.
for i in range(1, 6): print(i)
1 2 3 4 5
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.
Print numbers from 1 to 5 using a while loop.
i = 1 while i <= 5: print(i) i += 1
1 2 3 4 5
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
Stop printing numbers when the value reaches 5.
for i in range(1, 10): if i == 5: break print(i)
1 2 3 4
8.2 continue – Skip the current iteration
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
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.
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
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
ifruns a block only when a condition is Trueif–elsegives two paths — one always runselifladder handles multiple conditions in sequence- Nested
ifchecks dependent conditions inside each other forloop is used when iterations are known in advancewhileloop runs as long as a condition is Truebreakexits the loop,continueskips the iteration,passdoes nothing- Loop
elseruns 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!
Comments
Post a Comment