Course: Python

Progress (0%)

# Exercise: Sorted Numbers

Exercise 3 Very easy

Prerequisites for the exercise

1. Python Data Types
2. All previous chapters

## Objective

Output three input numbers in ascending order.

## Description

Ask the user to input three different integers by means of three different input prompts.

The general form of all the three input prompts together is shown as follows:

x: <input>
y: <input>
z: <input>

Once this is done, finally output these numbers in ascending order (i.e. smallest number first, largest number last) in the following format .

Sorted numbers: <int1> <int2> <int3>

Where `<int1>`, `<int2>`, and `<int3>`, are the input numbers.

Below shown is an example:

x: 150
y: 32
z: 50
Sorted numbers: 32 50 150

## New file

Inside the directory you created for this course on Python, create a new folder called Exercise-3-Sorted-Numbers and put the .py solution files for this exercise within it.

## Solution

We need to get three inputs from the user, hence we start by laying out three different `input()` calls.

One is for `x`, the second is for `y`, and the third for `z`.

``````x = input('x: ')
y = input('y: ')
z = input('z: ')``````

With this done, we then convert each input value into an integer; as always, using `int()`:

``````x = input('x: ')
y = input('y: ')
z = input('z: ')

x = int(x)
y = int(y)
z = int(z)``````

Then we create a list `ints` holding these three integers (`x`, `y` and `z`) followed by calling the `sort()` method on the list. The list is needed so that we could easily sort the numbers.

``````x = input('x: ')
y = input('y: ')
z = input('z: ')

x = int(x)
y = int(y)
z = int(z)

ints = [x, y, z]

# sort ints in ascending order
ints.sort()``````
Sorting numbers in Python without having a list can be an extremely challenging task!

To end with, we print all the three elements of the list (which is now in sorted order), one after another by means of passing them as arguments to `print()`.

``````x = input('x: ')
y = input('y: ')
z = input('z: ')

x = int(x)
y = int(y)
z = int(z)

ints = [x, y, z]

# Sort ints in ascending order.
ints.sort()

print('Sorted numbers:', ints[0], ints[1], ints[2])``````

This completes our exercise!

Note that the code shown here can be shortened down quite a bit.

We could inline the calls to `int()` where we call `input()`, as shown below:

``````x = int(input('x: '))
y = int(input('y: '))
z = int(input('z: '))

ints = [x, y, z]

# Sort ints in ascending order.
ints.sort()

print('Sorted numbers:', ints[0], ints[1], ints[2])``````

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage