0

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 pay.

Here's what I came up with:

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

Of course, I receive the error:

TypeError: can't multiply sequence by non-int of type 'str'

How can I tell Python that the results of the input should be regarded as integers rather than strings?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Ken B
  • 1
  • 1
  • 1
  • 1

3 Answers3

3

Any input from the input function is stored as string, you have to convert them both to integers before multiplying like this:

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

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
Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53
0

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.

Ken B
  • 1
  • 1
  • 1
  • 1
  • Whoa! Didn't get notified that I received some answers. Now I see there are a couple of different ways to do it. Many thanks to all. – Ken B Feb 25 '17 at 22:42