Skip to main content
 首页 » 编程设计

Python:除了 ValueError 仅适用于字符串。

2025年05月04日21think

在 Python 3.3 中有没有办法只排除字符串的 ValueError?如果我在 k 中键入一个字符串,我希望打印“无法将字符串转换为 float ”,而不是“无法取负数的平方根”。

while True: 
    try: 
        k = float(input("Number? ")) 

....

    except ValueError: 
        print ("Cannot take the square root of a negative number") 
        break 
    except ValueError: 
        print ("Could not convert string to float") 
        break 

请您参考如下方法:

如果要根据异常的来源处理不同的异常,最好将可能抛出异常的不同代码部分分开。然后你可以在抛出异常的相应语句周围放置一个 try/except block ,例如:

while True: 
    try: 
        k = float(input("Number? ")) 
    except ValueError: 
        print ("Could not convert string to float") 
        break 
    try: 
        s = math.sqrt(k) 
    except ValueError: 
        print ("Cannot take the square root of a negative number") 
        break