Skip to main content
 首页 » 编程设计

python之在此程序中使用 try 和 except 在此 python 中

2025年05月04日15sxdcgaq8080

你能告诉我为什么在下面的代码中使用 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') 

请您参考如下方法:

如果用户输入无法转换为 float 的内容,程序将异常停止。 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'之前停止。