0

Here is the code I have written. Everything runs as expected. My question is, when I type a non-integer and receive the Error message the Pay is still printed with the repeating non-integer entered. How can I fix what I have to either not print Pay or leave it blank?

Output

hours = input("Enter Hours: ")

rate = input("Enter Rate: ")

ot_rate = 1.5

try:
    hours = int(hours)
    rate = int(rate)
except:print("ERROR, please enter numeric input")

def computepay(hours, rate):
    if hours > 40:
        ot_hr = hours - 40
        hours -= ot_hr 
        ot_pay = ((ot_hr) * (rate) * (ot_rate))
        return (hours * rate) + ot_pay
    else:
        return (hours * rate)

print("Pay:")

print(computepay(hours, rate))
John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • Neither of your last two print statements are inside of a conditional, so of course they are always executed. You could have the input statements inside of a while loop which is only exited upon valid input. – John Coleman Nov 18 '18 at 20:19
  • Unrelated, but is casting hours and rate to `int` really what you want here? What if someone enters 7.5 hours? It will only pay them for 7. What if there rate is 15.50 per hour, it will only pay them, 15. – SuperShoot Nov 18 '18 at 22:32

2 Answers2

1

If user's input is non numeric you only print ERROR and let program go on instead of aborting program or asking again for input. Here's code that will ask user for input until they type only numeric values.

ot_rate = 1.5

while True:
    hours = input("Enter Hours: ")
    rate = input("Enter Rate: ")
    try:
        hours = int(hours)
        rate = int(rate)
        break
    except:
        print("ERROR, please enter numeric input")

def computepay(hours, rate):
    if hours > 40:
        ot_hr = hours - 40
        hours -= ot_hr 
        ot_pay = ((ot_hr) * (rate) * (ot_rate))
        return (hours * rate) + ot_pay
    else:
        return (hours * rate)

print("Pay:")
print(computepay(hours, rate))
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
0

Before your print statement you could check to make sure that the input is not a string:

if((isinstance(hours,int) or isinstance(hours,float)) and (isinstance(rate,int) or isinstance(rate,float)):    
    print(computepay(hours, rate))
else:
    print("Error Message")
AnnaB
  • 121
  • 2
  • 7