1

I am trying to convert a string input to a float after the input is given. Leaving the option to do something with the input if it is a string. I have tried some things but they give back the following error:

"TypeError: can't multiply sequence by non-int of type 'float' on line 8"

Below is code that works, but I want to keep the input a string and convert to float after the input is given:

def computepay(h,r):
    if h<=40:
        return h*r
    else:
        return h*r+((h-40)*b)
h = float(input("Enter Hours:"))
r = float(input("Enter Rate:"))
b = 0.5*r
p = computepay(h,r)
print(p)

How would this be done correctly?

Thanks!

2
  • Leave it as a string and only convert to float when you need it? I'm not quite sure what you're asking here... what's the exact issue you're facing as I can't see how that code will produce that error.... Commented Aug 26, 2018 at 14:13
  • Just to keep open that in the future I might want to look at how giving non-numericals as an input can be recognized as- or converted to a float; e.g. 'hundred' being recognized as '100' and dealt with as such in later lines. The error is produced when I do the following for instance: float(h) & float(r) after the input lines. Commented Aug 26, 2018 at 14:59

1 Answer 1

1

You can convert to float as a separate step and create new variables to hold your float values. This will leave your original inputs as strings.

h = input("Enter Hours:")
r = input("Enter Rate:")

h_float, r_float = map(float, (h, r))

b = 0.5 * r_float
p = computepay(h_float, r_float)

Alternatively, you can use the more verbose syntax:

h_float = float(h)
r_float = float(r)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.