SyntaxError
語法錯誤
ValueError
情況一:user輸入非期望資料型別
x = int(input("What's x? "))
print(f"x is {x}")
如果使用者輸入 cat
,會得到 ValueError: invalid literal for int() with base 10: 'catcat'
解決方案:
try:
x = int(input("What's x? "))
print(f"x is {x}")
except ValueError:
print("x is not an interger")
try & except
python關鍵字
NameError
doing sth with a variable that u shouldn't
try:
x = int(input("What's x? "))
except ValueError:
print("x is not an interger")
print(f"x is {x}")
如果輸入 wolffy
,返回 x is not an interger
和NameError: name 'x' is not defined
,因為在 int
接收字串輸入的時候就已經發生了ValueError,右邊的值並未賦給左邊。
賦值即定義?
增加else
try:
x = int(input("What's x? "))
except ValueError:
print("x is not an interger")
else:
print(f"x is {x}")
如果try成功了,沒出現Error,就會執行print(x);如果try失敗,執行except來處理ValueError,然後跳出程式
else的作用是避免已經出現錯誤後繼續執行程式
改進
直到user輸入合法才停止
while True:
try:
x = int(input("What's x? "))
except ValueError:
print("x is not an interger")
else:
break
print(f"x is {x}")
pass
跳過某種情況,catch it, and ignore it
例如:
except ValueError:
pass
Pythonic: try things, hopefully they work, but if they don't, handle the exception
不同於C的使用if