The program snippets below, written in python, converts distances in m to km or in cm to km
depending on the choice of the user.
The mathematical algorithm for converting distances from m to km or from cm to km is shown
below.
distance m
- distance km = e.g. to convert 3,000 m to km, we do:
1000
3000 m
distance km =
1000
= 3 km
distance cm
- distance km = e.g. to convert 500,000 cm to km, we do:
100000
500000 m
distance km =
100000
= 5 km
1. The python program below implements the above example algorithms :
2. DistanceMetre = 3000
3. DistanceKilometre = DistanceMetre / 1000
4. print(“3000 m when converted to km gives ”,
DistanceKiloMetre , “ km”)
5. DistanceCentimetre = 500000
6. DistanceKilometre = DistanceCentimetre / 100000
7. print(“500000 cm when converted to km gives ”,
DistanceKiloMetre , “ km”)
Create a file, name it convert.py, and save it on your desktop.
Open the IDLE IDE and import convert.py, then click the Run button. Write down
exactly what is output to the screen in your computing exercise book.
[5]
8. The same algorithm is implemented in the other program below, with variable inputs.
Distance = int(input(“enter a distance you wish to
convert: “))
unit = input(“enter either cm or m for a unit of the
distance entered: “)
if unit = = “cm”:
DistanceKilometre = distance / 100000
if unit = = “m”:
DistanceKilometre =distance / 1000
print(distance, “ ”, unit, “ when converted to km gives ”,
DistanceKiloMetre , “ km”)
Create another file, name it convert2.py, and save it on your desktop.
Open the IDLE IDE and import convert2.py, then click the Run button. Follow the
prompts and enter what is asked. Again write down exactly what is output to the screen in
your computing exercise book.
[5]