Python course menu
Python if Statement: Run Code Only When a Condition Is True
Learn the Python if statement for beginners: conditions, indentation, comparison and logical operators, truthy values like empty lists, membership checks with in, and common mistakes.
On this page
Programs need to make decisions: show a warning if the battery is low, give a discount if the order is large, refuse a login if the password is wrong. The if statement runs a block of code only when a condition is true.
Syntax#
if condition:
# runs only when condition is True
statement- The line starts with
if, then a condition, then a colon. - The code to run is indented (4 spaces). That indented block is the body of the
if.
Your first if#
temperature = 34
if temperature > 30:
print("It's hot today")
print("Drink some water")
print("Have a nice day")It's hot today
Drink some water
Have a nice dayChange the temperature to 22 and run it again:
Have a nice dayThe condition 22 > 30 is False, so Python skips the whole indented block. print("Have a nice day") is not indented, so it always runs.
What counts as a condition?#
A condition is anything Python can treat as true or false. Usually it is a comparison:
Combine conditions with and, or and not (see Operators):
name = "Asha"
if name.startswith("A") and len(name) > 3:
print("Long name starting with A")Long name starting with AChecking membership with in#
username = "admin"
if username in ("admin", "root"):
print("Admin account")Admin accountThis is cleaner than username == "admin" or username == "root".
Truthy and falsy conditions#
You do not always need a comparison. Empty values count as False and non-empty ones as True (see Type Conversion):
cart = []
if cart:
print("Ready to check out")
if not cart:
print("Your cart is empty")Your cart is emptyif cart: reads naturally as "if the cart has anything in it". This style is preferred over if len(cart) > 0:.
A practical example#
balance = 500
withdraw = 700
if withdraw > balance:
print("Insufficient funds")
print(f"Balance: {balance}")Insufficient funds
Balance: 500To do something else when the condition is false, you need if-else.
Common mistakes#
Practice#
Practice exercise
Write a program with a variable stock = 3. If stock is below 5, print Low stock: reorder soon. Then, whatever happens, print Stock level: 3.
Show hint
One if with an indented print, then a non-indented print that uses an f-string.
Show solution
stock = 3
if stock < 5:
print("Low stock: reorder soon")
print(f"Stock level: {stock}")Low stock: reorder soon
Stock level: 3Key takeaway#
Finished this lesson?