Monday 31 August 2020

Lesson Quattro

 

Now we would explore applications of the Python built-in function, input.

Let us write a little program that converts kilometres to miles.

1 km is equal to 0.621 miles. Or miles = km multiplied by 0.621.

Before we continue, how are the numbers 4 and 4.0 different? To a human, they are both the same, both are number four. However, to Python, they are two different types of numbers.

4 is an integer (whole number) whereas 4.0 is called a floating-point or float in Python. Therefore, to multiply or divide two numbers that are likely to have decimal places you have to make the conversion to float.

Let us comment put the previous lines of code before we begin. Then type in

                mi = km * 0.621

We need the user to enter the value for km to be converted. So we can insert that line first

                km = input(‘Please enter distance in kilometres: ‘)

                mi = km* 0.621

                print(mi)

Remember, we would be multiplying our input with a decimal number, in that case, we need to include float to the input else we get an error message. So our code now becomes

                km = float(input(‘Please enter distance in kilometres: ‘))

                mi = km* 0.621

                print(mi)

Let us run the code and supply 10 as input. We get an output of 6.21 as shown below

We could make the output to actually, say 6.21 miles by including this in the print line by adding the string ‘miles’. Thus the code now becomes

We could also print the output using the f’ string method with a placeholder { } when we write the print statement. Let’s add the line below then run the code again

                print(f’{mi} miles’)

We get the same output as can be seen below

There are other creative ways of improving output. For example, we could add the string ’10 km in miles is ‘ before printing the output. We can achieve this using both print options

                print(km,’in miles is’,mi,’miles’)

print(f’{km} in miles is {mi} miles’)

When we run the code again and input 10 we get the same output from both print options.

You could also print a heading that says what this program does whenever you run it. You can print that at the top before taking inputs

                print(‘KILOMETRE TO MILES CONVERTER’)

Now the program looks like this

Congratulation!

You have written a code that converts kilometres to miles.

We could as well easily change the code to a mile to kilometres converter or even a kilogram to pounds converter or vice versa.

This is the end of Part One of our course. Well done!

We would do a few exercises in subsequent lessons before proceeding to part Two.


No comments:

Post a Comment