Python Arena
Step 1 of 4

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")
Input
15
Output
Your age: 15
Youth ticket: 6 euros

This 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!")
Input
34
Output
Your 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")
Input
7
Output
Type a whole number: 7
7 is odd

The 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")
Python stops with
  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".

Your task

Challenge 1 of 3

Fill in the blank so the quiz says Not quite. It's Jupiter. for any other answer:

What is the largest planet? Jupiter
Correct!

Challenge 2

A minibus has rows of 4 seats, and passengers fill the rows from the front. Write a program that asks how many passengers there are. If they fill every row exactly, it prints Every row is full. Otherwise it prints how many passengers sit in the last row.

Passengers: 10
Passengers in the last row: 2

Challenge 3

An online shop charges 5 euros for shipping, but shipping is free for orders of 50 euros or more. Write a program that asks for the order total (in whole euros) and prints the shipping cost and the total to pay. Store the shipping cost in a variable in each branch, and print both lines after the conditional statement.

Order total: 30
Shipping: 5 euros
To pay: 35 euros