Zero to Python Hero - Part 4/10 : Control Flow: If, Loops & More (with code examples)

Control flow if loops

A major element of any programming language is the capability to take decisions and repeat them -this is the so-called control flow. Control flow is a feature available in Python that enables us to have the control of how code is run with conditions and repetition. The article includes such important Python control flow mechanisms as conditional statements, loops, special loop controls, list comprehensions, and even the new syntax of pattern matching introduced in Python 3.10.

Topics covered in this article

  1. Conditional Statements: if, elif, else
  2. Loops in Python: while and for
  3. Using range() and enumerate()
  4. Loop Control: break, continue, pass
  5. List Comprehensions
  6. Pattern Matching (Python 3.10+)

1. Conditional Statements: if, elif, else

The fundamental way of decision-making in Python is the application of an if statement. Depending on the truth or falseness of a condition, we are at liberty to implement a specific block of code.

if condition:
    # block of code
elif another_condition:
    # block of code
else:
    # block of code
 Example:
age = 18
if age >= 21:
    print("You can legally drink.")
elif age >= 18:
    print("You can vote but not drink.")
else:
    print("You're too young for both.")

Notes:

  • Python defines its blocks without the use of {}, using indents (which are typically 4 spaces) instead.
  • With elif, it is possible to check several conditions.

2. Loops in Python: while and for

Python has two significant types of loops including while and for.

while Loop

While loop will run a block of code continuously until the condition is True.

while condition:
    # loop body

Example:
count = 1
while count <= 5:
    print("Count:", count)
    count += 1

for Loop

The for mechanism is applied to iteration of sequences (lists, tuples, strings etc.).

for variable in sequence:
    # loop body
 Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

3. range() and enumerate()

range()

The range() produces a series of numbers typically employed in the for statement.

for i in range(5):  # i from 0 to 4
    print(i)
You can also specify the start, stop, and step:
for i in range(1, 10, 2):  # i = 1, 3, 5, 7, 9
    print(i)

enumerate()

enumerate() is useful when you want to have index and value when cycling through a list via enumerate().

colors = ['red', 'green', 'blue']
for index, color in enumerate(colors):
    print(f"{index}: {color}")

 4. Loop Control: break, continue, pass

These statements allow fine control over loop execution.

🔸 break
Terminates the loop entirely.
for num in range(1, 10):
    if num == 5:
        break
    print(num)

🔸 continue
Skips the current iteration and moves to the next.
for num in range(1, 6):
    if num == 3:
        continue
    print(num)

🔸 pass
Does nothing—used as a placeholder.
for letter in "hello":
    if letter == 'e':
        pass  # maybe we'll add logic later
    print(letter)

5. List Comprehensions

A A concise means of forming new lists by applying an expression to every one of the items of a sequence.

# Syntax:
new_list = [expression for item in iterable if condition]
# Basic Example:
squares = [x**2 for x in range(1, 6)]
print(squares)  # Output: [1, 4, 9, 16, 25]

# With Condition:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # Output: [0, 4, 16, 36, 64]

# Nested Comprehension:
matrix = [[row * col for col in range(3)] for row in range(3)]
print(matrix)  # Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

6. Pattern Matching

The Structural Pattern Matching is a new feature that appeared in Python 3.10. It is like switch-case in the other languages, but with stronger power.

match variable:
    case pattern1:
        # block
    case pattern2:
        # block
    case _:
        # default block

# Example:
status_code = 404

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")
    case _:
        print("Unknown Error")
Pattern Matching with Tuples:
point = (0, 1)

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y-axis at y={y}")
    case (x, 0):
        print(f"X-axis at x={x}")
    case (x, y):
        print(f"Point at x={x}, y={y}")

Pattern Matching with Classes:

class Dog:
    def __init__(self, breed):
        self.breed = breed

pet = Dog("Labrador")

match pet:
    case Dog(breed="Labrador"):
        print("It's a Lab!")
    case Dog(breed=other):
        print(f"It's a {other}!")

 Practice Problems

  1. Write a program to check if a number is positive, negative, or zero.
  2. Print numbers from 1 to 100, but break the loop if a number is divisible by both 3 and 5.
  3. Create a list of all vowels in a given sentence using list comprehension.
  4. Use enumerate() to print the index and character in a string.

Create a pattern matching function that returns the type of geometric shape based on the number of sides: 3 = Triangle, 4 = Square, etc.

ConceptDescriptionSyntax/Example
if, elif, elseConditional execution of code blocksif a > b: …
while, forRepetition of tasksfor x in y: …
range()Generate sequence of numbersrange(1, 5)
enumerate()Access index and value from iterablefor i, v in enumerate(list)
break, continueControl loop executionif x == 5: break
passPlaceholder with no actionif condition: pass
List ComprehensionOne-liner for generating lists[x for x in range(5)]
Pattern MatchingNew syntax from Python 3.10+ to match structuresmatch x: case …

Conclusion

The control flow provides you power and flexibility in your Python programs. Conditionals, loops, and comprehensions allow you to write clearly, effectively, poetically, and concisely. Since Python still keeps evolving, such as its pattern matching features, the possibility of writing comprehensible and potent code increases. Keep exercising these notions, experiment with your implementations and create the projects that depend on the dynamic decisions and iterations.

FAQ’s

1. What is control flow in Python?
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a Python program. It includes conditional statements (if, elif, else), loops (for, while), and control statements like break, continue, and pass.

2. When should I use a for loop vs a while loop?
Use a for loop when you know in advance how many times you want to iterate, especially over a sequence (like a list or range). Use a while loop when the number of iterations isn’t known and you want to loop until a specific condition becomes false.

3. What is the difference between break, continue, and pass?

  • break stops the loop entirely.
  • continue skips the current iteration and moves to the next one.
  • pass does nothing—it’s a placeholder used when the code block is required syntactically but no action is needed.

4. What is a list comprehension and why is it useful?
List comprehension is a concise way to create lists in Python. It reduces multiple lines of for loops and append() calls into a single line, making your code cleaner and more readable.

5. What is pattern matching in Python and how is it different from if-elif?
Pattern matching, introduced in Python 3.10, allows you to match complex data structures like tuples, lists, and objects more elegantly than with nested if-elif conditions. It’s similar to switch-case in other languages but far more powerful and expressive.

If you haven’t read the previous Lessons, you can check it out below:

Author

  • Rajesh data analytics and AI

    Rajesh Yerremshetty is an IIT Roorkee MBA graduate with 10 years of experience in Data Analytics and AI. He has worked with leading organizations, including CarDekho.com, Vansun Media Tech Pvt. Ltd., and STRIKIN.com, driving innovative solutions and business growth through data-driven insights.

    View all posts
Spread the knowledge
 
  

Leave a Reply

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