Often, you want a piece of your code to run only under specific circumstances. Just like in real life where you might decide "If it's raining, I'll take an umbrella," programs need a way to make decisions based on conditions. Python's fundamental tool for this is the if
statement.
The if
statement allows you to execute a block of code conditionally. It checks if a particular condition is true. If it is, the code block associated with the if
statement runs. If the condition is false, that block of code is skipped entirely, and the program continues with the next instruction after the if
block.
if
StatementThe basic syntax looks like this:
if condition:
# Code to execute if the condition is True
statement1
statement2
# ... more statements ...
# Code here runs regardless of the condition, after the if block
next_statement
Let's break this down:
if
Keyword: The statement starts with the keyword if
.condition
: This is an expression that evaluates to either True
or False
. This is often called a boolean expression. You typically use comparison operators (like ==
, !=
, <
, >
, <=
, >=
) or logical operators (and
, or
, not
) here, which you encountered in the previous chapter. You can also directly use a boolean variable.:
: A colon must follow the condition. This signifies the start of the code block that depends on the condition.if condition:
line, and indented further to the right, form the if
block. Python uses indentation (typically 4 spaces) to define code blocks. All lines indented at the same level under the if
belong to that block. The first line that is not indented at this level marks the end of the if
block.Imagine you're writing a program that checks if a user is old enough to vote. The voting age is usually 18.
age = 20
print("Checking voting eligibility...")
if age >= 18:
print("You are old enough to vote.")
print("Please register if you haven't already.")
print("Eligibility check complete.")
Let's trace the execution:
age
is assigned the value 20
.if
statement checks the condition age >= 18
. Since 20 >= 18
is True
, the condition is met.True
, the indented block is executed:
if
block finishes, the program continues with the next unindented line, printing "Eligibility check complete.".Now, what if the age
was different?
age = 15
print("Checking voting eligibility...")
if age >= 18:
# This block will be skipped
print("You are old enough to vote.")
print("Please register if you haven't already.")
print("Eligibility check complete.")
Execution trace:
age
is assigned 15
.if
statement checks age >= 18
. Since 15 >= 18
is False
, the condition is not met.False
, the entire indented block under the if
is skipped.if
block and prints "Eligibility check complete.".Indentation is not just for readability in Python; it's part of the syntax. It tells the interpreter which statements belong to the if
block. Incorrect indentation will lead to errors or unexpected behavior.
# Correct indentation
temperature = 30
if temperature > 25:
print("It's a warm day.") # Indented correctly
print("Wear light clothes.") # Indented correctly
# Incorrect indentation (will cause an IndentationError)
# if temperature > 25:
# print("It's a warm day.") # Missing indentation
Always use consistent indentation, typically 4 spaces per level. Most code editors will help you with this automatically.
We can visualize the decision-making process of an if
statement using a flowchart:
Flowchart showing the execution path of an
if
statement. If the condition evaluates to True, theif
block code is executed before continuing. If False, theif
block is skipped.
The if
statement is the simplest way to introduce conditional logic into your programs. It allows your code to react differently based on specific conditions, making your programs more dynamic and intelligent. As you'll see next, you can build upon this foundation using elif
and else
to handle alternative conditions.
© 2025 ApX Machine Learning