【问题标题】:Use of try and except in this python in this program在这个程序的这个 python 中使用 try 和 except
【发布时间】:2016-03-10 17:46:47
【问题描述】:

你能告诉我为什么在下面的代码中使用了 try 和 except 吗? 为什么分数=-1?我的意思是为什么只有-1

inp = input('Enter score: ')
    try:
        score = float(inp)
    except:
        score = -1

if score > 1.0 or score < 0.0:
       print ('Bad score')
   elif score > 0.9:
     print ('A')
   elif score > 0.8:
     print ('B')
   elif score > 0.7:
     print ('C')
   elif score > 0.6:
     print ('D')
   else:
     print ('F')

我们不能使用下面没有 try 和 except 命令的代码。

 score = float(input('Enter score: '))
   if score > 1.0 or score < 0.0:
       print ('Bad score')
   elif score > 0.9:
       print ('A')
   elif score > 0.8:
       print ('B')
   elif score > 0.7:
       print ('C')
   elif score > 0.6:
       print ('D')
   else:
       print ('F')

【问题讨论】:

  • @elegent: 呃,if not(0. &lt;= score &lt;= 1.):?
  • @HughBothwell:是的 :) 谢谢你是对的!

标签: python python-3.x try-catch except


【解决方案1】:

如果用户输入了无法转换为浮点数的内容,程序将因异常而停止。 try 捕捉到这一点并使用默认值。

这可行:

inp = input('Enter score: ')
try:
    score = float(inp)
except ValueError:
    print('bad score')

你的版本:

score = float(input('Enter score: '))
if score > 1.0 or score < 0.0:
     print ('Bad score')

例如,如果用户输入abc,则会在此行float(input('Enter score: ')) 上抛出ValueError。你的程序会在你打印Bad score'之前停止。

【讨论】:

    【解决方案2】:

    try-except 块在那里是因为用户可能输入了无效的浮点数。例如,“无”。在这种情况下,python 会抛出一个ValueError。使用不受限制的except 是非常糟糕的风格,所以代码应该已经阅读了

    try:
        score = float(inp)
    except ValueError:
        score = -1
    

    它被设置为-1,因为其余代码将负分视为非法输入,因此任何非法行为都会在不终止程序的情况下得到解决。

    【讨论】:

    • 你的意思是,应该是except ValueError:
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多