Conditional statements let your code make decisions. Python uses if, elif, and else to handle different situations based on conditions.
The basic if statement
An if statement checks a condition. If the condition is True, the code block inside runs.
age = 18
if age >= 18:
print("You can vote.")
The colon : is required after the condition. The indented lines (usually 4 spaces) form the code block that runs when the condition is True.
If the condition is False, the block is skipped.
Adding else
Use else to specify what happens when the if condition is False.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
No condition is needed after else.
Using elif for multiple conditions
For more than two possibilities, use elif (short for "else if") to check additional conditions.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Python checks the conditions from top to bottom and runs only the first block where the condition is True.
Common examples
Check if a number is positive, negative, or zero:
number = -5
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
Combine multiple conditions with and, or, and not:
temperature = 25
is_raining = False
if temperature > 30 and not is_raining:
print("Great day for the beach!")
else:
print("Maybe stay inside.")
Important notes
- Always include the colon
:afterif,elif, andelse. - Keep indentation consistent (Python uses it to define code blocks).
- Only one block executes: the first True condition (or
elseif none are True).
Quick summary
-
ifchecks the first condition. -
elifadds more conditions to check. -
elsehandles all remaining cases. - Indentation defines the code blocks.
Practice writing simple programs that make decisions. Conditional statements form the basis of logic in Python programs.
Top comments (0)