Python:除了字符串的ValueError.

Ace*_*Ace 1 python except

Python 3.3中除了字符串的ValueError之外还有一种方法吗?如果我在k中键入一个字符串,我想要打印"无法将字符串转换为浮点数",而不是"不能取负数的平方根".

while True:
    try:
        k = float(input("Number? "))
Run Code Online (Sandbox Code Playgroud)

....

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

Mic*_*rer 6

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

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
Run Code Online (Sandbox Code Playgroud)