Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The print function
Variables
Math in Python
The input function
19. Convert between types
Summary

Instruction

Perfect! input() is a very convenient function, but there is one catch: user input is always treated as a string value, even if a number is provided. If you ask for a number with input() and then try to add it to another number, Python will throw an error.

Luckily, we can use functions that convert between data types:

  • str(x) converts x into a string,
  • int(x) converts x into an integer,
  • float(x) converts x into a floating point number.

Here is a simple program that converts kilometers to miles:

distance_kilometers = input('How many kilometers have you driven? ')
distance_miles = float(distance_kilometers) // 1.60934
print('This means you have driven', distance_miles, 'miles!')

float(distance_kilometers) converts user input into a number of the float type. Without this conversion, we wouldn't be able to calculate distance_miles.

Exercise

Write a program that will ask the user for an hourly rate (prompt: What is your hourly rate?) and the number of hours worked (prompt: How many hours have you worked?). Then, show the following: You have earned {hourly_rate * count_hours} in total!

Use conversion to float.

Stuck? Here's a hint!

To calculate the total earnings, use:

float(hourly_rate)*float(count_hours)