Control Flow - If Statements and Loops in Python

Overview

In this lesson, we’ll explore the control flow tools in Python, including if statements, loops (for and while), and how they enable decision-making and repetition in your code. By the end, you’ll understand how to use these tools to control the execution flow of your Python programs.

Introduction

Control flow is fundamental in programming, allowing you to execute code blocks conditionally or repeatedly. Python provides simple and intuitive syntax for control flow mechanisms, making your code more dynamic and responsive to different conditions and inputs.

If Statements

  • Purpose: To execute a block of code only if a specified condition is true.
  • Syntax: ```python if condition: # code to execute if condition is true elif another_condition: # code to execute if another_condition is true else: # code to execute if no conditions above are true

  • Example:
    age = 20
    if age >= 18:
    print("You are an adult.")
    else:
    print("You are a minor.")
    

Loops

For Loops

  • Purpose: To iterate over a sequence (like a list, tuple, or string) or other iterable objects.

  • Syntax:

for element in sequence:
    # code to execute for each element
  • Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

While Loops

  • Purpose: To execute a block of code as long as a condition is true.

  • Syntax:

while condition:
    # code to execute while the condition is true

Example:

count = 0
while count < 5:
    print(count)
    count += 1

Break and Continue

  • break: Used to exit a loop prematurely.

  • continue: Skips the rest of the code inside a loop for the current iteration and goes to the next iteration.

  • Example:

    for number in range(10):
      if number == 5:
          break  # Exit the loop when number is 5
      print(number)
    

Nested Loops and Conditions

You can nest loops and if statements within each other to achieve complex decision-making and iterations.

  • Example:
    for x in range(3):
      for y in range(3):
          if x == y:
              continue  # Skip the iteration when x is equal to y
          print(f"Pair: ({x}, {y})")
    

Conclusion

Understanding and utilizing control flow with if statements and loops are crucial for creating dynamic and efficient Python programs. They allow you to handle different scenarios and perform repetitive tasks efficiently.