Python If Else
Conditional statements let a Python program choose which block of code to run based on whether a condition is true or false.
Making decisions with if
Most useful programs need to react differently depending on their data. The if statement is Python's basic tool for this: it evaluates a condition, and when that condition is true, it runs the indented block that follows. If the condition is false, that block is skipped entirely.
A condition is any expression that Python can interpret as true or false. Comparisons such as greater-than, less-than, and equality are the most common, and they rely on operators like >, <, >=, <=, == and !=.
A simple if statement
temperature = 32
if temperature > 30:
print("It is a hot day.")
print("Remember to drink water.")Adding elif and else
A lone if can only answer one question. To handle several possibilities you chain conditions together. The elif keyword (short for "else if") checks another condition only when the earlier ones were false, and else provides a fallback that runs when none of the conditions matched.
if, elif and else together
score = 74
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print("Your grade is", grade)Python checks the branches from top to bottom and stops at the first condition that is true, running only that branch. Order therefore matters: place the most specific or highest-priority conditions first.
Combining conditions
You can join several tests in one condition using the logical operators and, or, and not. Use and when every part must be true, or when at least one part must be true, and not to reverse a result.
- and: true only when both sides are true, for example age >= 18 and has_id.
- or: true when at least one side is true, for example is_weekend or is_holiday.
- not: flips the value, so not is_ready is true when is_ready is false.
- A one-line shorthand exists too: print("Adult") if age >= 18 else print("Minor").
Exercise: Python If...Else
Which keyword lets you test another condition after an if fails?