Difficulty: Beginner
Conditional statements allow your program to make decisions and execute different blocks of code based on whether a condition evaluates to True or False. The if statement is the most fundamental control flow tool in Python.
Python uses `if`, `elif` (short for else-if), and `else` keywords to build conditional logic. Unlike many other languages, Python relies on indentation rather than braces to define code blocks. Each condition is followed by a colon, and the indented block beneath it runs only when that condition is True.
You can nest conditions inside one another for more complex decision trees. However, deeply nested conditions can make code harder to read, so it is often better to use elif chains or combine conditions with logical operators (`and`, `or`, `not`).
Python also supports a concise ternary (conditional) expression: `value_if_true if condition else value_if_false`. This is useful for simple assignments but should not replace full if/else blocks when logic is complex.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score: {score}, Grade: {grade}")
Python checks each condition from top to bottom. The first True condition runs its block and the rest are skipped. Since 85 >= 80 is True, grade is set to 'B'.
age = 25
has_license = True
has_insurance = True
if age >= 18:
if has_license and has_insurance:
print("You can drive.")
elif has_license:
print("You need insurance.")
else:
print("You need a license.")
else:
print("You are too young to drive.")
The outer if checks age. If that passes, the inner conditions check for license and insurance using logical AND. Nesting lets you build layered decision logic.
num = 7
result = "even" if num % 2 == 0 else "odd"
print(f"{num} is {result}")
# Ternary in a function call
x, y = 10, 20
print(f"Max: {x if x > y else y}")
The ternary expression evaluates the condition in the middle. If True, it returns the left value; otherwise, the right value. It is a single-line alternative to a simple if/else.
values = [0, 1, "", "hello", None, [], [1, 2]]
for v in values:
if v:
print(f"{str(v):>10} -> truthy")
else:
print(f"{str(v):>10} -> falsy")
Python treats 0, empty strings, None, and empty collections as falsy. Everything else is truthy. Understanding this is crucial for writing clean conditional logic.
if statement, elif, else, nested conditions, ternary operator