5 min read
ā¢Question 7 of 41easyConditionals in Python
If-else statements in Python.
What You'll Learn
- Python's conditional syntax (if, elif, else)
- Comparison and logical operators
- Ternary expressions
- Truthy and falsy values
- Pattern matching (Python 3.10+)
Understanding Conditionals
Conditionals allow your code to make decisions based on conditions. Python uses indentation (not braces) to define code blocks, making the structure clean and readable.
If Statement
code.pyPython
age = 18
if age >= 18:
print("You are an adult")
print("You can vote")
# Single line (not recommended for complex logic)
if age >= 18: print("Adult")If-Else
code.pyPython
age = 15
if age >= 18:
print("Adult")
else:
print("Minor")If-Elif-Else
Use elif for multiple conditions (short for "else if"):
code.pyPython
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: BComparison Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal | x == 5 |
!= | Not equal | x != 5 |
> | Greater than | x > 5 |
< | Less than | x < 5 |
>= | Greater or equal | x >= 5 |
<= | Less or equal | x <= 5 |
is | Same object | x is None |
in | Membership | x in list |
code.pyPython
# Chained comparisons (Pythonic!)
x = 5
if 0 < x < 10:
print("x is between 0 and 10")
# Equivalent to: 0 < x and x < 10Logical Operators
code.pyPython
age = 25
has_license = True
# and - both must be True
if age >= 18 and has_license:
print("Can drive")
# or - at least one must be True
if age < 18 or not has_license:
print("Cannot drive")
# not - negation
if not has_license:
print("Need a license")
# Combining operators
if (age >= 18 and has_license) or is_emergency:
print("Can drive")Ternary Operator (Conditional Expression)
Single-line conditional assignment:
code.pyPython
age = 20
# Syntax: value_if_true if condition else value_if_false
status = "Adult" if age >= 18 else "Minor"
# With function calls
message = greet() if user else "Guest"
# Nested (avoid - hard to read)
result = "A" if score >= 90 else "B" if score >= 80 else "C"Truthy and Falsy Values
Python evaluates these as False:
NoneFalse- Zero:
0,0.0,0j - Empty sequences:
"",[],(),{},set()
Everything else is True:
code.pyPython
# Using truthiness
items = []
if items:
print("Has items")
else:
print("Empty list") # This prints
# Common patterns
name = user_input or "Default" # Use default if empty
# Check for None specifically
if value is None:
print("Value is None")
# Check for empty (any falsy value)
if not value:
print("Value is empty/None/zero")Match Statement (Python 3.10+)
Pattern matching - similar to switch/case:
code.pyPython
command = "start"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case "restart":
print("Restarting...")
case _: # Default case (wildcard)
print("Unknown command")
# Pattern matching with values
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On x-axis at {x}")
case (0, y):
print(f"On y-axis at {y}")
case (x, y):
print(f"Point at ({x}, {y})")Interview Tip
When asked about Python conditionals:
- Explain indentation-based blocks (no braces)
- Know the difference between
==andis - Understand truthy/falsy values
- Use chained comparisons (
0 < x < 10) - Mention pattern matching for Python 3.10+
- Ternary syntax:
a if condition else b