Python: Control Flow (If, Else, Loops)

When you’re first learning how to program, one of the most empowering ideas is that your code can make decisions based on specific conditions—rather than just running in a straight line from top to bottom. In Python, that capability comes from control flow statements: if, else, elif, and loops like for and while. By mastering these constructs, you’ll be able to write programs that respond dynamically to user input, handle repetitive tasks, and solve more complex logic problems with ease.

1. Using If, Else, and Elif

Why Conditionals Matter
  • Decision-Making: In real-world scenarios, you often need to process data differently depending on its values or states.
  • Multiple Paths: Python’s if, elif, and else let you define multiple branches, so your script can follow one path if a condition is True or another if it’s False.
Example – Basic If-Else
SQL
grade = 85

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
else:
    print("C or below")

In this snippet:

  • If grade is 90 or higher, the program prints “A”.
  • If it’s 80 to 89, it prints “B”.
  • Otherwise, it falls into the else clause: “C or below”.

2. Looping with For Loops

When to Use For Loops
  • Known Range: For loops are perfect when you know up front how many times to iterate—like when you’re reading from a fixed list or counting within a specific range.
  • Iterating Over Containers: They naturally handle lists, tuples, strings, and more, letting you process each element systematically.
Example – Summing a List
SQL
nums = [2, 4, 6, 8]
total = 0

for n in nums:
    total += n

print(total)  # Outputs: 20

By running through each element of nums, the loop accumulates a grand total, then displays it.

3. Looping with While Loops

When to Use While Loops
  • Open-Ended Repetition: If you need to keep running code until something changes dynamically, while is ideal (e.g., user enters “quit,” or a certain condition becomes False).
  • Interactive Prompts: Great for prompt-based or interactive programs where you can’t predetermine how many times a user might try.
Example – Counting Down
SQL
count = 5

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

This script counts down from 5 to 1, then displays “Blast off!” once count is no longer positive.

4. Combining Conditions & Loops

  • Skip or Stop: Inside a loop, you can use continue to skip certain iterations or break to exit prematurely.
  • Nested Logic: By nesting loops and conditionals, you can tackle more complex tasks, like scanning two-dimensional data or comparing sets of values simultaneously.
Example – Skipping a Number
SQL
numbers = [1, 2, 3, 4, 5]

for n in numbers:
    if n == 3:
        continue  # Skip 3
    print(n)
# Output: 1, 2, 4, 5

Practical Tips

  • Plan Your Logic First: Before writing a line of code, think about the condition(s) you need. Which path leads to what result?
  • Use elif: Chain multiple conditions cleanly (instead of multiple separate ifs). This keeps your logic organized.
  • Test Edge Cases: For loops, test an empty list; for while loops, test boundary conditions. For conditionals, test extremes (highest, lowest) and typical values.

Conclusion

Mastering if, else, elif statements and loop structures (for and while) empowers you to write Python programs that can decide, repeat, or terminate based on dynamic conditions. Whether you need to stop reading a file after detecting an error or sum only even numbers in a range, Python’s control flow constructs make it straightforward—and, with good planning, your code becomes both efficient and easy to follow.

Python Exercises – Control Flow (If, Else, Loops)

Python Exercises – Control Flow (If, Else, Loops)

Ask Tutor
Tutor Chat