Skip to main content
 首页 » 编程设计

python之无法让我的 else 语句在 while 循环中打印

2025年04月02日8JustinYoung

对于 Python 来说仍然很新,所以如果这里有任何问题,我深表歉意。这适用于您输入数字并返回值的程序。你必须输入一个数字,所以当用户输入一个字符串时,我试图让它说“需要不同的值”。但是,我在输入周围有一个 int() ,这意味着当我输入一个字符串时出现以下错误:

ValueError: invalid literal for int() with base 10

我的代码如下:

while True: 
 OVR = int(input('OVR?')) 
 if OVR == 0: 
   break 
 elif OVR < 50: 
   print('0.75M') 
 elif OVR >= 50 and OVR < 60: 
   print('8M') 
 elif OVR >= 60 and OVR <= 70: 
   print('15M') 
 elif OVR > 70 and OVR <= 82: 
   print('30M') 
 elif OVR > 82: 
   print("He's the GOAT, what do you think he wants?") 
 else: 
   print('different values needed') 

我知道拥有所有这些 elif 可能不是一个好主意,所以我最终会将其整合到一个公式中。如前所述,我的主要目标是我想这样做,以便在用户输入字符串时打印“需要不同的值”。我考虑过 try/except 语句,但如果我正确理解它们,它们并不是真正用于计算和打印的东西,也不能使用这些 elif。

请您参考如下方法:

将 int 转换包装在 try/except block 中。

while True: 
    try: 
        OVR = int(input('OVR?')) 
    except ValueError: 
        print('different values needed') 
        continue 
    # OVR an integer value, handle it as needed...