Exercise On Variables and Input Functions

Question:

Create a program that asks the user for a number of kilometers, converts it to miles, and prints the results to the user.

To perform this exercise, you need the conversion rate:

1 mile = 1.609344 km

Good luck, and when you finish, come back here to see the solution.

 

  • We are starting a new file. In your Python interpreter, go to File from the menu.
  • Then select the new file where we are going to write our computer program.
  • Save your file as Ex01_km2miles for easy identification.


We will get the number of km, divide by the conversion rate, and print the output.

 

Follow the red comments in the program carefully.









Now run your program:









  • As you can see, our program has been beautifully executed. The user input has made our program interactive for the user.
  • But you notice our program has so many decimal places, so we are going to round it using the round() function.
  • So let's go back to our program and edit our program.








 When rounding the number of miles, we punctuate it with a comma (,)) and type the number of places we want to run it to.







And now we have only 4 decimal places. Fantastic, our program is working!

We will learn more functions like this when we learn about numbers.

 Summary

km = float( input("Type the number of kilometers: ") )
miles = km / 1.609344

print(km, "km = ", round(miles,4), "miles")

Output:

Type the number of kilometers: 34
34.0 km =  21.1266 miles

If you have any questions feel free to leave it in the comment section.

Good luck happy coding!


No comments:

Post a Comment

Python Programming Tutorial 15

 Error Handling Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we d...