Course contentsShow
← Python
Lesson 15 of 1,0601. Foundations and EnvironmentFree lesson

Implementing Conditional Logic with If Statements

You will learn how to control the execution path of your program by evaluating boolean expressions and executing specific code blocks accordingly.

Controlling Program Flow with If Statements

In this lesson, you will learn how to make your programs "think" by executing specific code only when certain conditions are met.

Up until now, your Python scripts have been linear—they run from the top line to the bottom line in order. However, real-world software needs to make decisions. For example, a program might need to check if a user is old enough to access a feature or if a number is positive. This is where the if statement comes in.

Evaluating Boolean Expressions

An if statement works by evaluating a boolean expression (a statement that results in True or False). If the condition is True, Python executes the indented block of code immediately following the statement. If the condition is False, Python skips that block entirely.

Consider this example:

# A simple decision-making script
age = 18

if age >= 18:
    print("You are eligible to vote!")

In this code, we compare the variable age against the value 18. Because 18 >= 18 is True, the print function runs. If we changed age to 16, the condition would become False, and the program would simply finish without printing anything.

The Importance of Indentation

Remember from our previous lesson on code blocks that Python relies on indentation to know which lines belong to the if statement. Everything you want to run conditionally must be indented under the if line.

user_input = input("Enter a secret password: ")

if user_input == "Python123":
    print("Access Granted.")
    print("Welcome to the system!")

In the example above, both print statements are indented. This means they are both part of the "conditional block." If the password is correct, both lines execute. If it is wrong, both are skipped. This structure allows you to build complex logic by simply grouping relevant actions together under a single decision point.

Key Takeaway: The if statement acts as a gateway that only allows code to execute when its boolean condition evaluates to True.