Control Structures in Python

Overview

In this lesson, we’ll delve into the control structures in Python, which include conditional statements, loops, and comprehension expressions. These structures allow you to control the flow of your Python program based on conditions and iterations. By the end of this lesson, you’ll understand how to use if, elif, and else statements, for and while loops, and comprehension techniques to make your code more efficient and readable.

Introduction

Control structures are fundamental programming constructs that enable decision-making, looping, and iteration over collections. Python provides a straightforward and elegant syntax for these structures, making your code both efficient and easily understandable.

Conditional Statements (if, elif, else)

  • Purpose: To execute code based on certain conditions.

  • Syntax:

if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition2 is True
else:
    # code to execute if neither condition1 nor condition2 is True

Example:

age = 18
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 item in sequence:
    # code to execute for each item

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

Loop Control Statements

  • Purpose: To control the flow of loops.

  • Statements:
    • break: Terminates the loop and transfers control to the statement immediately following the loop.
    • continue: Skips the rest of the code inside the loop for the current iteration and continues with the next iteration.
  • Example:
for i in range(10):
    if i == 3:
        continue
    if i == 7:
        break
    print(i)

Comprehension Expressions

  • Purpose: To provide a concise way to create lists, dictionaries, sets, and generators from existing iterables.

  • List Comprehension Example:

squares = [x**2 for x in range(1, 6)]
  • Dictionary Comprehension Example:
squares_dict = {x: x**2 for x in range(1, 6)}
  • Set Comprehension Example:
odd_numbers = {x for x in range(10) if x % 2 != 0}

Conclusion

Control structures in Python, including conditional statements and loops, are essential for adding logic and flow to your programs. Understanding these constructs allows you to tackle more complex problems by breaking them down into manageable parts that can be conditionally executed or iterated over. Comprehensions provide an efficient and readable way to create new collections based on existing ones.