【问题标题】:Try except not catching error尝试除了不捕获错误
【发布时间】:2017-05-01 16:08:23
【问题描述】:

如果输入不是数字,我正在尝试添加错误消息。我试过try/except,现在尝试if/else,但两者都没有被激活(例如,如果用户输入“百分之十”,则有一个错误输出与我的错误消息相比)

第一个根据百分比输入计算成绩。第二个应该是计算工资。

grade=eval(input("Enter Score:"))
try:
    if(grade<0 or grade>1):
        print("Bad Score")
    elif(grade>=0.9):
        print("A")
    elif(grade<=0.9 and grade>=0.8):
        print("B")
    elif(grade<=0.8 and grade>=0.7):
        print("C")
    elif(grade<=0.7 and grade>=0.6):
        print("D")
    else:
        print("F")
 except:
     print("Bad score")

Hours=eval(input('Please enter hours worked: '))
Rate=eval(input('Please enter pay per hour: '))
if(Hours<=40 and Hours>=0):
    Pay=Hours*Rate
elif(Hours>40):
    Pay=((Hours-40)*(1.5*Rate))+(40*Rate)
    print('Your pay should be $',Pay)
else:
    print('Error.  Please enter a Numeric Value')

已编辑格式化...原始帖子中的代码是正确的,但必须缩进以创建代码灰色框,从而创建不正确的缩进。

再次感谢您!

【问题讨论】:

  • Fix the indentation。你的代码甚至不会像现在这样运行。
  • @jonrsharpe 也不是 eval..
  • 谢谢大家!这个链接就是我要找的。​​span>
  • 对于未来的提问者,以防万一,这虽然是一个好主意。再次感谢您的检查。 while True: try:grade=float(input("Enter Score:")) except ValueError: print("Bad score") continue else: break

标签: python python-3.x if-statement try-except


【解决方案1】:

错误的缩进!尝试并期望应该去那里自己的路线。像这样:

grade=eval(input("Enter Score:"))
try:
  if(grade<0 or grade>1):
     print("Bad Score")
  elif(grade>=0.9):
     print("A")
  elif(grade<=0.9 and grade>=0.8):
     print("B")
  elif(grade<=0.8 and grade>=0.7):
     print("C")
  elif(grade<=0.7 and grade>=0.6):
     print("D")
  else:
     print("F")
except:
print("Bad score")

Hours=eval(input('Please enter hours worked: '))
Rate=eval(input('Please enter pay per hour: '))
if(Hours<=40 and Hours>=0):
  Pay=Hours*Rate
elif(Hours>40):
  Pay=((Hours-40)*(1.5*Rate))+(40*Rate)
  print('Your pay should be $',Pay)
else:
  print('Error.  Please enter a Numeric Value')

【讨论】:

  • 您的print("Bad score") 缩进不正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-21
相关资源
最近更新 更多