Two branches with else
Often a program should do one thing when a condition is true and something else when it's false. With what you know so far, you would write two if statements with opposite conditions:
age = int(input("Your age: "))
if age < 18:
print("Youth ticket: 6 euros")
if age >= 18:
print("Adult ticket: 10 euros")
15Your age: 15
Youth ticket: 6 eurosThis works, but the two conditions must fit together exactly. Change the 18 in one of them and forget the other, and some ages get two tickets or none at all.
else
An else branch runs when the condition of its if is false. It covers every other case, so it needs no condition of its own:
age = int(input("Your age: "))
if age < 18:
print("Youth ticket: 6 euros")
else:
print("Adult ticket: 10 euros")
print("Enjoy the movie!")
34Your age: 34
Adult ticket: 10 euros
Enjoy the movie!else is followed by a colon and its own indented block, and it's at the same indentation as its if. Exactly one of the two blocks runs, never both and never neither. Together the if and the else form one conditional statement, so an else can't stand on its own: it always comes right after the block of an if.
Even or odd
A number is even when dividing it by 2 leaves no remainder. Without else, telling even and odd numbers apart takes two if statements. With else, one condition is enough:
number = int(input("Type a whole number: "))
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
7Type a whole number: 7
7 is oddThe same idea tells whether one number divides another evenly: minutes % 60 == 0 is true when the minutes make whole hours.
A common mistake is to give else a condition, as if it were another if:
temperature = 15
if temperature > 20:
print("Wear shorts")
else temperature <= 20:
print("Wear jeans")
File "main.py", line 4
else temperature <= 20:
^^^^^^^^^^^
SyntaxError: expected ':'Python expects the colon right after else. Leave the condition out: else already means "in every other case".