An if on its own does nothing when the condition fails. But often you want a reply either way: "if you passed, congratulations, otherwise try again". That is what else is for.
books = 80
if books == 100:
print("Reading Champion Badge!")
else:
print("Let's try a little more!")Let's try a little more!
Exactly one of the two paths runs: the if block when the condition is True, the else block when it is False.
else: starts at the beginning of the line (level with the if), ends with a colon, and never has a condition after it.Comparison operators
A condition is not only "equals". You can ask: bigger? smaller? not equal?
| Operator | Meaning | Example (age = 15) | Result |
|---|---|---|---|
| == | equal to | age == 15 | True |
| != | not equal to | age != 15 | False |
| > | greater than | age > 15 | False |
| < | less than | age < 18 | True |
| >= | greater than or equal to | age >= 15 | True |
| <= | less than or equal to | age <= 16 | True |
english = 70
if english >= 65:
print("Pass")
else:
print("Fail")Pass
> does not include the value itself; >= does: 65 > 65 is False, 65 >= 65 is True. The = always comes after > or <; => is an error.Comparing text
Text can be compared with == and != too. Careful: "not rainy" does not mean "sunny"; a cloudy day is not rainy either:
weather = "Cloudy"
if weather != "Rainy":
print("Play soccer")
else:
print("Stay inside")Play soccer
Practice
Assign 777 to lucky. If lucky equals 777, print Lucky!; otherwise print Try again.
Press Run to see the result. Change the condition so it prints Practice worksheet when chem is 40 or less, otherwise No worksheet.
chem = 28
if chem == 40:
print("Practice worksheet")
else:
print("No worksheet")Press Run to see the result. Complete the condition: if height is greater than 132, print Available; otherwise Unavailable.
height = 91
if ___:
print("Available")
else:
print("Unavailable")Press Run to see the result. Assign 15 to age. If age is 65 or more, print Slide closed; otherwise print Slide OK.
Press Run to see the result. Complete the condition: if myScore is not equal to 100, print Aim for a perfect score!; otherwise print Perfect!
myScore = 90
if ___:
print("Aim for a perfect score!")
else:
print("Perfect!")Press Run to see the result. Assign 17 to number. If its remainder when divided by 2 is 0, print Even; otherwise print Odd.
Hint
The remainder operator is%.Press Run to see the result. The school trip costs 350 pounds and Sara has 280 in money. If money is enough (350 or more), print You can join the trip; otherwise print what is missing as You need 70 more (calculate it in code).
Press Run to see the result. Key points
if condition:thenelse:; exactly one path runs, and else has no condition.- Comparison operators:
== != > < >= <=;>=includes the value itself. - Text can be compared with
==and!=.