Python if else and conditional logic
if statement, elif chain, else clause, nested conditionals, truthy and falsy values, ternary expression
Conditional Flow
Conditionals let your program take different paths based on a value. The colon and indented block are mandatory.
score = 72
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # C
Truthy and Falsy
Python evaluates any value as boolean in a condition. Falsy values: 0, 0.0, "", [], {}, None, False. Everything else is truthy.
name = ""
if name:
print("Hello,", name)
else:
print("No name provided") # runs
Ternary Expression
For a single-line conditional assignment, use the ternary form. Keep it readable โ do not nest ternary expressions.
x = 10
label = "even" if x % 2 == 0 else "odd"
print(label) # even
Avoid deeply nested if blocks. If nesting exceeds two levels, consider restructuring with early returns or helper functions.
Conditionals are the decision-making backbone of any program. Keep your conditions simple and readable โ if a condition needs a comment to explain it, extract it into a well-named boolean variable. Deeply nested if-blocks are a sign the logic should be refactored, often with early returns or guard clauses. Python does not have a switch/match statement in older versions, but Python 3.10 introduced match for structural pattern matching, which is powerful for dispatching on data structures. For now, elif chains are idiomatic and readable.
