The Box Swap Puzzle

How many steps would it take to move the chicken into box b and the elephant into box a, knowing that you cannot have more than one animal per box?

View Solution

Using variables

In a computer program, variables are used to hold values that the program will be abe to access and change if necessary. Variables can contain different types of values such as strings (e.g. “Hello World”), numbers (integers or reals) or Boolean (True or False) values.

Each variable is given a meaningful identifier, chosen by the programmer such as message, playerName, score, numberOfLives.

The assignment operator = is used to assign/store a value to a variable.


The Swapping Puzzle

Let’s replace the cardboard boxes from the above box swap puzzle with three variables called a, b and temp. We can initialise our variables a and b with their initial values as follows:

We can solve the above puzzle to swap the content of our two variables using the same three-step approach as follows:

Your Challenge

Write a program that asks the user to enter two values between 1 and 10 and assign these values to two variables called number1 and number2.

Add some code to ensure that number1 ends up with the highest of the two values and number2 with the lowest of the two values. In other words, if number1 is smaller than number2, swap the content of the variables number1 and number2.

Output number1 and number2 on screen.

To complete this challenge, you will have to complete the Python code below:

Extension Task

Extend your code to retrieve three user inputs and swap these to display them in ascending order.


Share Button