**Python: Control Flow

This lesson introduces control flow in Python, essential for creating dynamic and interactive programs. You'll learn how to use conditional statements (if, elif, else) to make decisions and loops (for, while) to repeat tasks, controlling the order in which your code executes.

Learning Objectives

  • Understand and use `if`, `elif`, and `else` statements for conditional logic.
  • Implement `for` loops to iterate through sequences like lists and strings.
  • Employ `while` loops to repeat code blocks based on a condition.
  • Learn to use `break` and `continue` statements within loops to control execution flow.

Text-to-Speech

Listen to the lesson content

Lesson Content

Conditional Statements: Making Decisions

Conditional statements allow your program to make decisions based on certain conditions. The if statement evaluates a condition, and if it's true, the code block indented under the if statement is executed.

age = 20
if age >= 18:
    print("You are an adult.")

elif (else if) allows you to check for additional conditions if the previous if or elif conditions were false. The else statement provides a default code block to execute if none of the preceding conditions are true.

score = 75
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D")

For Loops: Iterating Through Sequences

for loops are used to iterate over a sequence (such as a list, tuple, string, or range). This means you can execute a block of code for each item in the sequence.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

You can also use for loops with the range() function to iterate a specific number of times:

for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

While Loops: Repeating Until a Condition is Met

while loops execute a block of code as long as a specified condition is true. Be careful to ensure your loop condition eventually becomes false to avoid infinite loops.

count = 0
while count < 3:
    print("Count:", count)
    count += 1

Inside loops, break stops the loop entirely, and continue skips the current iteration and goes to the next one.

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

for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i) # Prints only odd numbers
Progress
0%