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.")
Note: Python uses indentation, not curly braces, to mark the body of an if statement. Every line in the block must be indented by the same amount. Four spaces is the widely followed convention.

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.

KeywordPurposeHow often it may appear
ifStarts the decision and tests the first conditionExactly once per chain
elifTests an alternative condition when earlier ones failedZero or more times
elseCatches every case not handled aboveAt most once, at the end

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").
Note: Do not confuse == with =. A single equals sign assigns a value, while a double equals sign compares two values. Writing if x = 5 is a syntax error in Python.

Exercise: Python If...Else

Which keyword lets you test another condition after an if fails?