Pythonbeginner 7 min
Run code only when a condition is true, using if, elif and else.
How to compare values and choose between paths with if, elif and else.
Programs need to react: grant access, apply a discount, show a warning. Conditions are how they decide.
A condition is a question with a True or False answer. Comparisons create them:
== equal, != not equal> < >= <=Combine them with and, or and not.
An if statement ends with a colon, and the code that belongs to it is indented (four spaces is the convention). Indentation is how Python knows what is inside.
temperature is 28.28 > 30 is False, so the first block is skipped.elif temperature >= 20 is True, so it prints Nice weather.else is skipped because an earlier branch already ran.False: age >= 18 is False and and needs both sides True.Change temperature to 35 and then 10. Which message appears each time?
= instead of == in a condition. = assigns, == compares.if, elif or else.else if. Python's keyword is elif.==, !=, >, < and and / or / not.if, elif, else choose a block; the colon and indentation matter.Next: repeating work with loops.
if score >= 50:
print("Pass")
else:
print("Try again")temperature = 28
if temperature > 30:
print("It's hot. Drink water.")
elif temperature >= 20:
print("Nice weather.")
else:
print("Bring a jacket.")
age = 17
has_ticket = True
print(age >= 18 and has_ticket)