Lesson 9 of 30
Conditional Statements
if, elif, else — controlling the flow of your programs with conditionals.
The if Statement
Conditional statements allow your program to make decisions. Python uses indentation (4 spaces) to define code blocks — there are no curly braces.
temperature = 28
if temperature > 30:
print("It's hot outside.")
elif temperature > 20:
print("Nice and warm.")
elif temperature > 10:
print("A bit cool.")
else:
print("It's cold!")
# Output: Nice and warm.
Nested Conditionals
score = 85
if score >= 50:
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: B
Ternary (Conditional) Expression
age = 18
status = "adult" if age >= 18 else "minor"
print(status) # adult
Truthiness
In Python, the following values are falsy: 0, 0.0, "", [], {}, None, False. Everything else is truthy.
name = ""
if name:
print(f"Hello, {name}")
else:
print("No name provided.") # This runs