if Statements

Run different code depending on what's true

Beginner 9 min

In this lesson

An if statement lets your program choose what to do: it runs a block of code only when a condition is true, and optionally does something else otherwise. It’s how Python makes decisions instead of running every line top to bottom.

Explain it like I’m 5

An if is a fork in the road. Python checks a question that’s either yes or no, and only walks down the path that matches the answer.

The shape of an if statement

An if statement has a condition — an expression that evaluates to True or False — followed by a colon, then an indented block of code that runs only when the condition is true.

The indentation isn’t decoration: in Python it’s how you mark which lines belong to the if. Every line indented the same amount under the colon is ‘inside’ the block. When the indentation stops, the block ends.

Example
temperature = 30

if temperature > 25:
    print("It is warm.")
    print("Wear something light.")

print("Have a good day.")
Output
It is warm.
Wear something light.
Have a good day.
The indented block runs; the un-indented line always runs.

elif and else: covering the other cases

else runs when the if condition was false. elif (‘else if’) lets you test another condition only if the previous ones failed. Python checks them top to bottom and runs the first block whose condition is true — then skips the rest.

Use a plain if when conditions are independent (each should be checked). Use elif chains when exactly one branch should win.

Example
age = 17

if age >= 18:
    print("You can vote.")
elif age >= 16:
    print("Almost there.")
else:
    print("Still a few years to go.")
Output
Almost there.
An if/elif/else chain picks exactly one branch.

Change score and run it. Try values above 90, between 60 and 90, and below 60 to hit each branch.

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 60:
    print("Grade: Pass")
else:
    print("Grade: Try again")

What counts as a condition

Conditions are usually built from comparisons: == (equal), != (not equal), <, >, <=, >=. You combine them with and, or, and not. and is true only if both sides are true; or is true if either side is.

Watch the difference between = (assigns a value) and == (asks whether two values are equal). Using = in a condition is a common slip and Python will flag it.

Example
temperature = 30
is_raining = False

if temperature > 25 and not is_raining:
    print("Great day for a walk.")
Output
Great day for a walk.
Combining conditions with and / not.

Truthiness: values that act like True or False

You can put almost any value where a condition is expected. Empty things are ‘falsy’: 0, "" (empty string), [] (empty list), and None all count as false. Non-empty things are ‘truthy’. So if name: means ‘if name isn’t empty’.

Example
basket = []

if basket:
    print("Ready to check out.")
else:
    print("Your basket is empty.")
Output
Your basket is empty.
An empty list is falsy, so the else branch runs.

Nesting conditions (and keeping them shallow)

An if can live inside another if — a nested condition that’s only checked once an outer one has passed. It’s useful, but deep nesting quickly gets hard to follow, so keep it shallow: often an and or an early elif reads better than a second level of indentation.

When you only need to choose a value rather than run different code, the one-line conditional expression is tidier — that’s covered under operators.

Example
attended = True
score = 85

if attended:
    if score >= 60:
        print("Passed")
    else:
        print("Retake needed")
else:
    print("Did not attend")
Output
Passed
An inner condition checked only after the outer one passes.

Common mistake: Using = instead of == in a condition

Why it happens:

= means ‘assign’, but it’s easy to type it when you mean ‘compare’. Python raises a SyntaxError for if x = 5:.

How to fix it:

Use == to compare: if x == 5:. Reserve a single = for setting a variable’s value.

if x == 5:
    print("x is five")

Common mistake: Forgetting the colon or the indentation

Why it happens:

The : ends the condition and the indented block defines what runs. Leaving either out breaks the structure Python expects.

How to fix it:

End the if line with : and indent the body by four spaces.

In an if/elif/else chain, how many branches run?

Which operator checks whether two values are equal?

Mini exercise (easy)

Set a variable hour (0–23) and print ‘Good morning’ before 12, ‘Good afternoon’ from 12 to 17, and ‘Good evening’ otherwise.

Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.

def greeting(hour):
    # return "Good morning" (<12), "Good afternoon" (12-17), else "Good evening"
    return "Good morning"

print(greeting(9))

What to learn next

You learned how if, elif, and else let a program branch, how conditions are evaluated as True or False, and how indentation defines a block. You put it together in a greeting() function that returns a different message depending on the hour.

Decisions let your code choose; loops let it repeat, which is where computers really earn their keep. Loops: Repeating Work introduces the idea behind loops and the difference between for and while. When you’re ready, continue to the next lesson.