Skip to content
Laviyx Learn

Try

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.

Beginner5 min readUpdated
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#

Python
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#

Python
temperature = 34

if temperature > 30:
    print("It's hot today")
    print("Drink some water")

print("Have a nice day")
Output
It's hot today
Drink some water
Have a nice day

Change the temperature to 22 and run it again:

Output
Have a nice day

The 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:

ConditionMeaning
x == 5equal to
x != 5not equal to
x > 5, x < 5greater / less than
x >= 5, x <= 5greater / less than or equal
"a" in wordmembership

Combine conditions with and, or and not (see Operators):

Python
name = "Asha"
if name.startswith("A") and len(name) > 3:
    print("Long name starting with A")
Output
Long name starting with A

Checking membership with in#

Python
username = "admin"
if username in ("admin", "root"):
    print("Admin account")
Output
Admin account

This 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):

Python
cart = []

if cart:
    print("Ready to check out")
if not cart:
    print("Your cart is empty")
Output
Your cart is empty

if cart: reads naturally as "if the cart has anything in it". This style is preferred over if len(cart) > 0:.

A practical example#

Python
balance = 500
withdraw = 700

if withdraw > balance:
    print("Insufficient funds")

print(f"Balance: {balance}")
Output
Insufficient funds
Balance: 500

To 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
Python
stock = 3

if stock < 5:
    print("Low stock: reorder soon")

print(f"Stock level: {stock}")
Output
Low stock: reorder soon
Stock level: 3

Key takeaway#

Finished this lesson?