将非整数打印为输出



这是我编写的代码。一切都按预期进行。我的问题是,当我键入一个非整数并收到错误消息时,Pay仍会打印出重复输入的非整数。如何修复不打印"支付"或将其留空的问题?

输出

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))

如果用户的输入是非数字的,则只打印ERROR并让程序继续运行,而不是中止程序或再次请求输入。下面的代码将要求用户输入,直到他们只键入数值为止。

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))

在打印语句之前,您可以检查以确保输入不是字符串:

if((isinstance(hours,int) or isinstance(hours,float)) and (isinstance(rate,int) or isinstance(rate,float)):    
print(computepay(hours, rate))
else:
print("Error Message")

最新更新