Python Conditions
Making Decisions: Understanding Conditionals (if
, elif
, else
) in Python
Up to this point, your Python code has mostly run from top to bottom, executing each line in order. But real-world tasks and programs often need to do different things based on different situations.
Imagine you're writing a program:
- You need to show a welcome message, but a special message if the user is an administrator.
- You need to process a number, but only if it's positive.
- You need to decide what to do after a game level: go to the next level if the player won, or show a "Game Over" screen if they lost.
Programs need to make decisions. This is where conditional statements come in. They allow your code to choose which lines to run based on whether a certain condition is true or false.
What Are Conditional Statements?
Conditional statements are structures in Python that let you control the flow of your program. They allow a block of code to run only if a specified condition is met (is True
).
The main keywords used for conditionals are if
, elif
(short for "else if"), and else
.
The if
Statement (Do Something Only If True)
The basic if
statement checks if a condition is True
. If the condition is True
, the code block immediately following the if
line runs. If the condition is False
, that code block is skipped.
The syntax is:
if condition:
# Code block that runs IF the condition is True
statement_1
statement_2
...
Notice the colon :
at the end of the if
line and the indentation (spaces or tabs) before the code lines inside the block. Indentation is how Python knows which lines belong to the if
block.
Here are some examples using comparison operators (like >
and >=
):
score = 150
if score > 100:
print("High Score!")
print("Congratulations!")
# These two print lines run because the condition (score > 100) is True.
age = 17
if age >= 18:
print("You are old enough to enter.")
# This print line is skipped because the condition (age >= 18) is False.
The else
Statement (Do Something If if
is False)
The else
statement provides an alternative code block to run when the condition in the preceding if
statement is False
. It means "if the if
condition is not true, then do this instead".
The syntax is:
if condition:
# Code block for True
else:
# Code block that runs IF the condition is False
statement_A
statement_B
...
The else
line must be at the same indentation level as the if
line it belongs to.
In an if-else
structure, one of the two blocks will always run, but never both.
age = 17
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# Output: You are a minor. (Because age >= 18 is False)
score = 80
if score > 100:
print("High Score!")
else:
print("Keep playing!")
# Output: Keep playing! (Because score > 100 is False)
The elif
Statement (Checking Multiple Conditions)
When you have more than two possible outcomes or conditions to check, you use the elif
(short for "else if") statement. An elif
block is checked only if the preceding if
and any other elif
conditions in the chain were all False
.
You can have one if
, followed by any number of elif
blocks, and optionally one final else
block.
The syntax is:
if condition1:
# Code for condition1 True
elif condition2:
# Code for condition2 True (if condition1 was False)
elif condition3:
# Code for condition3 True (if condition1 and condition2 were False)
...
else:
# Code if ALL above conditions were False
Python checks the conditions one by one, from top to bottom. As soon as it finds a condition that is True
, it runs only the code block for that condition and then skips the rest of the elif
and else
parts in that structure. If none of the if
or elif
conditions are true, the else
block (if it exists) is executed.
temperature = 20
if temperature > 30:
print("It's hot!")
elif temperature > 25: # Is 20 > 25? False. Skip this block.
print("It's warm.")
elif temperature > 15: # Is 20 > 15? True. Run this block.
print("It's cool.")
elif temperature > 5: # This condition is True (20 > 5), but is skipped because the previous elif was already True.
print("It's a bit chilly.")
else:
print("It's cold.")
# Output based on temperature = 20: It's cool.
Only the code block for the first true condition is executed. If none of the conditions are true, the else
provides a default action.
What Can Be a Condition? (Truthiness)
The "condition" part of an if
or elif
statement must be something that Python can evaluate to either True
or False
.
Common things used as conditions include:
- Comparison Operations: Expressions using
==
,!=
,>
,<
,>=
,<=
. These comparisons directly result inTrue
orFalse
boolean values (e.g.,score > 100
). - Logical Operations: Combining other conditions or boolean values using
and
,or
, andnot
. (e.g.,if age > 18 and has_license:
). - Boolean Variables: Using a variable that already holds a
True
orFalse
value (e.g.,if is_game_over:
).
Python also automatically treats almost any object as either True
or False
when used in a conditional context. This is the concept of "truthiness" and "falsiness" we discussed in the Data Types article.
-
Objects considered "falsy" (evaluate to
False
in a condition) include:False
None
- The number
0
(integer or float) - Empty sequences like
""
(empty string),[]
(empty list),()
(empty tuple) - Empty collections like
{}
(empty dictionary),set()
(empty set)
-
Almost all other objects are considered "truthy" (evaluate to
True
in a condition), such as non-zero numbers, non-empty strings, and non-empty collections.
This allows for concise checks:
player_inventory = [] # An empty list
if player_inventory: # Python checks if player_inventory is "truthy" (it's empty, so it's falsy)
print("Inventory is not empty.")
else:
print("Inventory is empty.") # This line runs
# Output: Inventory is empty.
# ---
user_input = input("Please enter your name: ") # Let's say the user just presses Enter
if user_input: # Python checks if user_input is "truthy" (it's an empty string "", so it's falsy)
print(f"Hello, {user_input}!")
else:
print("Hello, nameless person!") # This line runs if the input was empty
# Output: Hello, nameless person!
Using if my_list:
as a shortcut for if len(my_list) > 0:
is very common in Python.
Indentation: Defining Code Blocks
We mentioned it earlier, but it's worth repeating: indentation is how Python groups lines of code into blocks belonging to an if
, elif
, or else
statement. All lines within the same block must have the exact same level of indentation, and they must be indented more than the if
/elif
/else
line above them.
is_player_alive = True
if is_player_alive:
# These two lines are INSIDE the if block because they are indented
print("Player is active.")
print("Game continues.")
# This line is OUTSIDE the if block because it's at the same level as 'if'
print("Checking game status.")
If you mix spaces and tabs for indentation, or use inconsistent spacing within a block, Python will give you an IndentationError
. It's standard practice to use 4 spaces for each level of indentation.
Nested Conditionals
You can place if
, elif
, or else
statements inside another if
, elif
, or else
block. This is called nesting and is used when you need to make a second decision only after a first decision has been made.
The inner blocks must be further indented relative to their containing conditional statement.
is_logged_in = True
user_role = "moderator" # Could be "user", "admin", "moderator"
if is_logged_in:
print("Welcome back!")
# Start of NESTED conditional block
if user_role == "admin":
print("You have administrator privileges.")
elif user_role == "moderator":
print("You have moderator privileges.")
else:
print("You have standard user privileges.")
# End of NESTED block
print("Access granted.") # This line is part of the OUTER if block
else:
print("Please log in to access the system.")
# If is_logged_in is True and user_role is "moderator", the output is:
# Welcome back!
# You have moderator privileges.
# Access granted.
Nested conditionals allow for complex decision logic, but make sure to keep track of your indentation!
Common Mistakes with Conditionals
- Missing the Colon: Forgetting the
:
at the end of theif
,elif
, orelse
line. - Incorrect Indentation: The most common issue! Lines in a block must be consistently indented.
- Using
=
instead of==
: Using the assignment operator (=
) instead of the comparison operator (==
) in a condition (if score = 100:
is wrong). Python will likely raise aSyntaxError
or behave unexpectedly. - Confusing
and
andor
: Make sure you useand
when all parts must be true, andor
when at least one part must be true. - Misunderstanding Truthiness: Forgetting that
0
,""
,[]
,None
, etc., are consideredFalse
in conditions can lead to unexpected behavior.
Conclusion
Conditional statements (if
, elif
, else
) are essential tools for controlling the flow of your program. They allow your code to react to different data and situations by choosing which specific blocks of code to execute.
- You learned how
if
runs a code block only if its condition isTrue
. - You learned how
else
provides a block to run when theif
condition isFalse
. - You learned how
elif
lets you check additional conditions in sequence when previous ones were false. - You reinforced that conditions must evaluate to
True
orFalse
(or Python determines their "truthiness"). - You saw the critical importance of indentation for defining which lines belong to each conditional block.
- You briefly saw how conditional statements can be nested for more complex decisions.
Mastering conditionals allows your programs to become much more intelligent and responsive. You can now make your programs follow different paths based on data!