Python Basics · Making Decisions · lesson 7 of 12
if, elif and else
about 12 minutes · free · runs in your browser
Step 1 of 2
Branching
if runs a block only when its condition is true:
temperature = 30
if temperature > 25:
print("Warm")
else:
print("Not warm")
Two things carry all the meaning here. The colon ends the condition, and the indentation marks the block. Python has no braces: the four spaces are the syntax. Get them wrong and the program means something different, or refuses to run.
For more than two outcomes, elif chains extra conditions. Python checks them in order
and takes the first that matches, then skips the rest:
if score >= 70:
grade = "A"
elif score >= 50:
grade = "B"
else:
grade = "C"
Order matters: if you tested score >= 50 first, a score of 90 would come out as B.
Your turn: set category from temperature — "hot" above 25, "mild" from
15 to 25, and "cold" below 15.
You start from this, and edit it in the browser:
temperature = 18
# Set category to "hot", "mild" or "cold".
Step 2 of 2
Wrapping a decision in a function
A decision is far more useful when you can apply it to any value rather than one fixed variable. That is what a function is for:
def describe(n):
if n > 0:
return "positive"
return "not positive"
def starts the definition, the name comes next, the inputs go in brackets, and the
body is indented. n is a parameter — a name for whatever value the caller hands
over, so those three lines work for every number rather than one.
Nothing runs until you call it. describe(5) runs the body with n set to 5:
describe(5) # "positive"
describe(-2) # "not positive"
return sends a value back to whoever called it, and stops the function immediately —
which is why the example needs no else. It is not print: printing puts text on the
screen and leaves the caller with nothing, and every exercise from here on reads what you
returned.
One more piece of syntax you will see in every starter: pass is Python's "deliberately
empty" placeholder, there because a def with an empty body is a syntax error. Delete it
and write the body in its place.
Your turn: write grade(score) returning "A" for 70 and above, "B" for 50 to
69, and "C" below 50.
You start from this, and edit it in the browser: