No history yet

Control Flow

Making Decisions with Code

So far, your code runs straight from top to bottom. But what if you want it to make choices? That's where control flow comes in. It's how we direct the path our program takes, letting it react differently to different situations.

Control flow in Python refers to the order in which statements are executed in a program.

The most basic way to make a decision is with an if statement. It checks if a certain condition is true. If it is, a specific block of code runs. If not, the program just skips it. Let's say we're checking if a user is old enough to see a movie.

age = 20

if age >= 18:
    print("You are old enough to enter.")

Because age is 20, the condition age >= 18 is true, and the message is printed. Notice the colon : at the end of the if line and the indentation on the next line. Python uses this indentation to know which code belongs to the if statement.

But what happens if the condition is false? This is where else comes in handy. It gives the program an alternative path to take.

age = 16

if age >= 18:
    print("You are old enough to enter.")
else:
    print("Sorry, you are not old enough.")

# Output: Sorry, you are not old enough.

Sometimes you have more than two possibilities. For this, you can use elif, which is short for "else if." It lets you check multiple conditions in order.

score = 85

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

# Output: Grade: B

Python checks each condition from top to bottom. As soon as it finds one that's true (score >= 80), it runs that block of code and skips the rest of the if-elif-else chain.

Repeating Actions

Decisions are powerful, but so is repetition. Loops allow you to run the same block of code multiple times. This is incredibly useful for working with collections of data, like lists.

The for loop is perfect for when you know how many times you want to repeat an action. It iterates over a sequence, like a list of numbers or strings, and performs an action for each item.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I like {fruit}s.")

# Output:
# I like apples.
# I like bananas.
# I like cherrys.

In this example, the variable fruit takes on the value of each item in the fruits list, one by one, until the list is exhausted. You can also loop a specific number of times using the range() function.

# The range(5) function generates numbers from 0 up to (but not including) 5.
for number in range(5):
    print(f"The current number is {number}")

# Output:
# The current number is 0
# The current number is 1
# The current number is 2
# The current number is 3
# The current number is 4

What if you don't know exactly how many times you need to loop? Maybe you want to keep doing something until a specific condition is met. For this, we use a while loop.

A while loop continues to execute as long as its condition remains true. It's like telling your program, "Keep doing this while this thing is true."

count = 0

while count < 3:
    print(f"The count is {count}")
    count = count + 1  # This is crucial!

print("Loop finished.")

# Output:
# The count is 0
# The count is 1
# The count is 2
# Loop finished.

It's vital to include a line inside the while loop that will eventually make the condition false. In the code above, count = count + 1 increases the value of count with each pass. Without it, count would always be 0, count < 3 would always be true, and the loop would run forever! This is called an infinite loop.

Now, let's test your understanding of these control flow structures.

Quiz Questions 1/5

What will the following Python code output?

Quiz Questions 2/5

Which statement is essential within a while loop to prevent it from running forever?

Mastering if, for, and while is fundamental. They are the building blocks that allow you to create programs that are smart, efficient, and dynamic.