我只是试图输入一个异常,用户输入一个非数字值,以便程序给出错误消息并退出。但是,像我一样使用quit()
,它仍然会尝试运行代码的结尾(variable not defined
错误),并给我一个内核已经死亡的错误。退出代码的正确方法是什么?
try:
inp=raw_input("Enter Hours Worked ")
hours=float(inp)
inp=raw_input("Enter Pay Rate ")
rate=float(inp)
except:
print "Error: Enter a numeric value"
quit()
if hours<=40:
pay = hours * rate
else:
pay = (hours-40) * rate * 1.5 + (40 * rate)
print "Gross Pay: $",pay
答案 0 :(得分:1)
sys.exit()
模块中您正在寻找的内容可能是sys
。
因此,如果您在所有内容的开头提供import sys
,则您的代码将如下所示:
try:
inp=raw_input("Enter Hours Worked ")
hours=float(inp)
inp=raw_input("Enter Pay Rate ")
rate=float(inp)
except:
print "Error: Enter a numeric value"
sys.exit() # use an exit code to signal the program was unsuccessful
if hours<=40:
pay = hours * rate
else:
pay = (hours-40) * rate * 1.5 + (40 * rate)
print "Gross Pay: $",pay