例1.使用 if 敘述句時未加上冒號
a = 15
if a > 5
print(a)
# SyntaxError: expected ':'
例2.進行判斷時,將 == 誤用為 =
a = '早安您好'
if a = '早安您好':
print('True')
# SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
例3.字串前後的引號不完全
name = 'Jason
print(name)
# SyntaxError: unterminated string literal
例4.使用內建關鍵字作為變數名稱
True = 'Jason'
print(True)
# SyntaxError: cannot assign to True
例1.使用尚未宣告的變數名稱
print(name + 3)
# NameError: name 'name' is not defined
例2.打錯變數名稱
country = ['美國', '德國', '法國', '英國']
print(countr[0])
# NameError: name 'countr' is not defined.
例1.試圖更改字串裡的特殊字元
name = 'Jason'
name[0] = 'L'
# TypeError: 'str' object does not support item assignment
例2.嘗試連接字串及非字串時
score = 90
addscore = '考試成績:' + score
# TypeError: can only concatenate str (not "int") to str
例3.迴圈條件設定錯誤
for i in 5:
print(i)
# TypeError: 'int' object is not iterable
# 正確寫法為 fot i in range(5)
例4.迴圈條件設定錯誤
database = [1, 2, 3, 4, 5, 6]
for i in range(database):
print(i)
# TypeError: 'list' object cannot be interpreted as an integer
# 正確寫法為 fot i in range(len(database))
例1.將非數字的字串轉換為整數、浮點數
print(int('HelloWorld'))
# ValueError: invalid literal for int() with base 10: 'HelloWorl
例1.未正確縮排
countries = ['美國', '英國', '法國', '德國']
for country in countries:
print(country)
# IndentationError: expected an indented block
例1.使用可用範圍之外的索引值
saySomething = "HelloWorld"
for i in range(len(saySomething) + 1):
print(saySomething[i], end='!')
# IndexError: string index out of range
例1.以零作為餘數
print(1 / 0)
# ZeroDivisionError: division by zero
表格整理:
例外類型 | 說明 |
---|---|
SyntaxError | 語法錯誤 |
NameError | 變數名稱錯誤 |
TypeError | 類型錯誤 |
ValueError | 值錯誤 |
IndentationError | 縮排錯誤 |
IndexError | 索引值錯誤 |
ZeroDivisionError | 除數為零的錯誤 |