Learn / Beginner / Lesson 9

Conditions

11 min Tested on Python 3.15Updated By
In short

if runs a block of code only when a condition is True; elif checks another condition and else catches everything left. Conditions use comparisons such as ==, < and in, combined with and, or and not. Python uses indentation, not brackets, to mark each block.

if, elif and else

Python
temperature = 18

if temperature > 25:
    print("Hot — shorts weather")
elif temperature > 15:
    print("Mild — bring a light jacket")
else:
    print("Cold — wear a coat")
Output
Mild — bring a light jacket
  • End each condition line with a colon :.
  • Indent the block underneath by 4 spaces. The indentation is the block.
  • Python checks from the top and runs only the first branch that's true.

Comparison operators

OperatorMeaningExample
==equalage == 18
!=not equalstatus != "done"
< <=less (or equal)price < 10
> >=greater (or equal)score >= 50
inis inside"@" in email
isis the same object (use for None)result is None

Combining conditions

Python
age = 34
has_ticket = True

if age >= 18 and has_ticket:
    print("Welcome in")

if not has_ticket or age < 18:
    print("Sorry")
else:
    print("Enjoy the show")

print(18 <= age < 65)   # chained comparison
Output
Welcome in
Enjoy the show
True

Truthy and falsy values

Python
for value in [0, 7, "", "hi", [], [1], None]:
    print(repr(value), bool(value))
Output
0 False
7 True
'' False
'hi' True
[] False
[1] True
None False

Empty things and zero count as false, so you can write if items: instead of if len(items) > 0:.

One-line conditional expression

Python
stock = 0
label = "in stock" if stock > 0 else "sold out"
print(label)
Output
sold out

match-case: choosing between many patterns

Python
def describe(command: str) -> str:
    match command.split():
        case ["go", direction]:
            return f"Walking {direction}"
        case ["pick", "up", item]:
            return f"You take the {item}"
        case ["quit" | "exit"]:
            return "Bye!"
        case _:
            return "I don't understand"

print(describe("go north"))
print(describe("pick up lamp"))
print(describe("exit"))
print(describe("dance"))
Output
Walking north
You take the lamp
Bye!
I don't understand

match (Python 3.10+) compares a value against shapes, not just single values, and can pull parts out into names. case _ catches everything else. For simple yes/no choices, if is still clearer.

Practice

Write grades for these scores: scores = [92, 75, 58, 81]. Print one line per score: A for 90 and above, B for 75–89, C for 60–74 and F below 60, formatted like 92: A.

Expected output:
92: A
75: B
58: F
81: B
Your code

Quick check

1. What does bool([]) give?

2. With x = 7, which branch runs: if x > 5: A, elif x > 3: B?

3. How should you check whether a value is None?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →