Skip to content

Conditionals

A name first assigned inside a branch belongs to that branch. Assign it before the if when the value is needed afterwards.

For a value that depends on a condition, the conditional expression a if test else b is often shorter.

def sign(x: num) -> str:
label = "positive"
if x < 0:
label = "negative"
elif x == 0:
label = "zero"
return label
print(sign(-2), sign(0), sign(5))
print("big" if 10 > 3 else "small")
Run in playground
Output
"negative" "zero" "positive"
"big"