Language:

Search

Python Control Flow — if/elif/else, for while Loops, break/continue/pass

Control flow decides what code runs and how many times. In this lesson, you’ll learn conditions (if/elif/else), loops (for, while), and loop controls (break, continue, pass) with clear examples.


1) Conditions: if, elif, else

Use conditions to run code only when a test is True.


age = 17
if age >= 18:
    print("You can vote.")
elif age >= 16:
    print("You can apply for a learner's driving permit.")
else:
    print("Focus on school and fun!")
  

Truthy & Falsy

These values count as False in conditions: 0, 0.0, '' (empty string), [], {}, set(), None. Everything else is True.


items = []
if items:            # empty list → False
    print("Has items")
else:
    print("No items")
  

Combining Conditions


temp = 28
is_raining = False
if temp > 25 and not is_raining:
    print("Go for a walk!")
  

2) for Loops

for loops iterate over a sequence (list, string, range, etc.).


# Iterate over a list
fruits = ["apple", "banana", "mango"]
for f in fruits:
    print(f)
# Iterate with index
for i, f in enumerate(fruits, start=1):
    print(i, f)
# Iterate a fixed number of times
for n in range(3):
    print("Hello", n)   # 0, 1, 2
  

for ... else (loop-else)

The else runs only if the loop did not break.


# Find the first even number; otherwise print "none found"
nums = [3, 5, 7]
for n in nums:
    if n % 2 == 0:
        print("First even:", n)
        break
else:
    print("No even numbers")
  

3) while Loops

Run while a condition remains True. Be careful to avoid infinite loops.


count = 3
while count > 0:
    print("Countdown:", count)
    count -= 1
print("Blast off!")
  

A Common Pattern: Input Validation


tries = 0
password = "python123"
while tries < 3:
    guess = input("Enter password: ")
    if guess == password:
        print("Welcome!")
        break
    tries += 1
else:
    print("Too many attempts.")
  

4) Loop Controls: break, continue, pass

break — stop the loop now


for n in range(1, 10):
    if n == 5:
        break
    print(n)
# prints 1..4 then stops
  

continue — skip this iteration


for n in range(1, 6):
    if n % 2 == 0:
        continue   # skip even numbers
    print(n)
# prints 1, 3, 5
  

pass — do nothing (placeholder)


for task in ["todo1", "todo2"]:
    # TODO: implement later
    pass
  

5) Practical Mini-Examples

a) Sum of numbers 1..100


total = 0
for n in range(1, 101):
    total += n
print(total)
  

b) FizzBuzz (classic)


for n in range(1, 21):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
  

c) Search with loop-else


names = ["Ali", "Ammar", "Sara"]
target = "Zain"
for name in names:
    if name == target:
        print("Found:", name)
        break
else:
    print("Not found")
  

Common Pitfalls & Tips

  • Indentation matters: every block under if, for, while must align.
  • Don’t modify a list while iterating it: iterate over a copy or build a new list.
  • Prefer enumerate() over range(len(...)): clearer and safer.
  • Use break early to exit when done: avoids extra work.
  • Leverage for ... else: perfect for “search or report not found”.

Ahmad Ali

Ahmad Ali

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies Cookie Policy