2016-01-22 42 views
0
try: 
    guess = str(int(input("Please enter your guess: "))) 
    assert len(guess) == 4 
except ValueError or AssertionError: 
    print("Please enter a 4 digit number as your guess not a word or a different digit number. ") 

斷言錯誤當我輸入一個不是4位的數字時收到。斷言錯誤,錯誤,當不應該有一個

回答

1

except ValueError or AssertionError:應該except (ValueError, AssertionError):

當你做or你是不是捕捉異常AssertionError

2

讓我們來分析代碼結構。我已經添加括號來表示解釋器組語句的Python 。

try: 
    do_something() 
except (ValueError or AssertionError): 
    handle_error() 

讓我們來看看發生了什麼異常的定義捕捉。引述official docs

表達x or y首先評估x;如果x爲真,則返回其值;否則,將評估y並返回結果值。

「如果x是真正的」 實際上指的是x在布爾上下文真(的x.__nonzero__()在Python 2值,在Python 3 x.__bool__())。除非另有規定,否則所有對象(包括類)都是隱含真實的。

# No exception is raised in either case 
assert ValueError 
assert AssertionError 
# both values after conversion are True 
assert bool(ValueError) is True 
assert bool(AssertionError) is True 

在服用類考慮布爾上下文和引用文檔關於布爾運算後,我們可以有把握地說asssume評估(ValueError or AssertionError)ValueError

要趕上多個例外,你需要把它們的元組:

try: 
    do_something() 
except (ValueError, AssertionError): 
    handle_error()