Course contentsShow
← Python
Lesson 73 of 1,0602. Control Flow and LogicFree lesson

Executing Code Based on Boolean Conditions

Learn to use the if statement to execute specific blocks of code only when a defined condition evaluates to True.

Making Decisions with if

In this lesson, you will learn how to make your programs "think" by using the if statement to run specific lines of code only when a condition is met.

The Power of Choice

So far, your programs have run every line of code from top to bottom, like a train on a single track. However, real-world logic often requires a "fork in the road." We use the if statement to check if a condition is True. If it is, Python executes the indented code block that follows; if it is False, Python skips that block entirely.

How it Works

To write an if statement, you provide the keyword if, followed by your boolean condition, and finish the line with a colon (:). Any code you want to run conditionally must be indented beneath that line.

Consider this example where we check if a user is old enough to access a specific feature:

age = 18

if age >= 18:
    print("Access granted! Welcome to the dashboard.")

print("This line runs regardless of the condition.")

In the code above, the first print function is indented, making it part of the if block. Because age >= 18 evaluates to True, the program prints "Access granted." The final print statement is not indented, so it executes every time, proving that the if block is just a temporary detour in your program's flow.

Watching the Indentation

Indentation is not optional in Python; it is the primary way Python determines which lines belong to your if condition. If you forget to indent, Python will raise an error. If you indent too much or too little, your logic might behave in ways you didn't intend. Keep your code clean, stick to the standard four-space indentation, and ensure your boolean conditions are clear. By controlling these paths, you transform your static scripts into dynamic, interactive programs.

Key Takeaway: The if statement acts as a gateway, executing an indented block of code only when the provided condition evaluates to True.