Skip to content Skip to sidebar Skip to footer

Python How To Multiply Results From Input Strings

I'm a programming beginner trying to learn Python. I'm trying to complete the following exercise: Write a program to prompt the user for hours and rate per hour to compute gross

Solution 1:

Of course you need to convert to appropriate type before multiplication, since input("") returns string of user input.

The conversion is as follows:

rate -> float
hours -> int

This is to make sure that you don't loose decimal points where user enter rate with decimals eg 2.2

So from your code you can add the following

hours = int(input("Enter number of hours worked\n"))
rate = float(input("Enter pay rate per hour\n"))
print(hours * rate) # int * float gives float

Solution 2:

Problem solved:

hours = int(input("Enter number of hours worked\n"))
rate = int(input("Enter pay rate per hour\n"))

I figured the int function had to be placed in there somewhere.

Post a Comment for "Python How To Multiply Results From Input Strings"