if condition: runs the indented block underneath when the condition is true. else: runs a different block otherwise. The colon and the indentation are the syntax: Python uses the indentation (four spaces by convention) to know which lines belong to the block, so keep it consistent.
A function that decides something usually returns from inside the branches. Once return runs, the function is over, so the code after the if only executes when the condition was false; that is why a trailing return often needs no else.
def sign(n):
if n < 0:
return "negative"
return "not negative"
print(sign(-4))Your task
Write describe_temp(c) that returns "cold" when the temperature is below 10, "mild" when it is below 25, and "hot" otherwise.
Hint 1
Check the coldest case first, return, then the next case.
Hint 2
Three outcomes need two conditions; the last one is whatever is left.
Show the solution
def describe_temp(c):
if c < 10:
return "cold"
if c < 25:
return "mild"
return "hot"