-2

I got stumbled at one exercise from the book Python for everybody could you help me pls?

Exercise 3: Write a program to prompt the user for hours and rate per hour to compute gross pay.

Enter Hours: 35

Enter Rate: 2.75

Pay: 96.25

i wrote that piece of code

#compute gross pay
prompt = 'Enter hours\n'
hours = input(prompt)
int(hours)
prompt = 'Enter rate\n'
rate = input(prompt)
int(rate)
pay = hours * rate
print(pay)

and i got an error message

Traceback (most recent call last):
  File "ex2_pay", line 8, in <module>
    pay = hours * rate
TypeError: can't multiply sequence by non-int of type 'str'

but i can not figure it out why. I did convert the return value to int

Raymond Reddington
  • 1,709
  • 1
  • 13
  • 21
Kieran
  • 25
  • 4
  • `int(hours)` doesn't update the value of the `input`. Save `int(hours)` in a variable or instead use `int(input("text"))` – vmemmap Aug 20 '20 at 13:25

2 Answers2

2

int(hours) and int(rate) don't actually do anything. You're casting these values to integer types, but ultimately not doing anything with the result. What you probably intended to do was assign them back to their original variables:

#compute gross pay
prompt = 'Enter hours\n'
hours = input(prompt)
hours = int(hours)
prompt = 'Enter rate\n'
rate = input(prompt)
rate = int(rate)
pay = hours * rate
print(pay)

Repl.it

However, you should consider making your code a bit more succinct, input tolerant and easier to read by combining a few lines and casting the inputs to floats (to handle decimals in addition to integers):

#compute gross pay
hours = float(input('Enter hours\n'))
rate = float(input('Enter rate\n'))
print(hours * rate)

Repl.it

esqew
  • 42,425
  • 27
  • 92
  • 132
  • `int("2.75")` will fail, because it cannot translate it into an integer. I think `float` would actually solve OP's problem. – Hampus Larsson Aug 20 '20 at 13:27
  • @HampusLarsson Great point - I've added that in my secondary "optimized" version of the OP's example. – esqew Aug 20 '20 at 13:29
  • It's not an optimization; `int` was never the correct type to use for defining the rate in the first place. (Though when dealing with money, `float` isn't the right type to use either, due to precision issues. `decimal.Decimal` would be more appropriate.) – chepner Aug 20 '20 at 14:30
0
hours = input('Enter hours\n')
hours = int(hours)
rate = input('Enter rate\n')
rate = int(rate)
pay = hours * rate
print(pay)

You can simplify your code and fix the int()

hedy
  • 1,160
  • 5
  • 23