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.


message = "Hello world!"
playerName = input("Enter your name")
score = 0
numberOfLives = 3

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:

a = "chicken"
b = "elephant"

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

a = "chicken"
b = "elephant"

temp = a
a = b
b = temp

print("Variable a = " + a)
print("Variable b = " + b)

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.




The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 11

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!