Python 之 程式設計中常見錯誤

2022-08-24 06:00:20 字數 2124 閱讀 4218

1 變數名不正確

message = "

hello

"print

(msg)

#錯誤資訊:nameerror: name 'msg' is not defined

2 單引號包圍的字串中包含單引號,雙引號包圍的字串中包含雙引號

message = '

he'llo'

print

(message)

#錯誤資訊:syntaxerror: invalid syntax

message = "

he"llo"

print

(message)

#錯誤資訊:syntaxerror: invalid syntax

3 型別錯誤

num1 = 1

print(1 + "2"

)#錯誤資訊:typeerror: unsupported operand type(s) for +: 'int' and 'str'

4 除0錯誤

num1 = 1

print(1 /0)

#錯誤資訊:zerodivisionerror: division by zero

5 列表下標越界

colors = ["

red","

blue

","yellow"]

print(colors[3])

#錯誤資訊:indexerror: list index out of range

6 for迴圈後面的**忘記縮排

colors = ["

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown"]

for color in

colors:

print

(color)

#錯誤資訊:indentationerror: expected an indented block

7 不必要的縮排

colors = ["

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown"]

print

(colors)

#錯誤資訊:indentationerror: unexpected indent

8 for迴圈忘了後面的冒號

colors = ["

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown"]

for color in

colors

print

(color)

#錯誤資訊:syntaxerror: invalid syntax

9 修改元組中的元素,引發型別錯誤

#

定義元組,使用圓括號而不是方括號

colors = ("

red", "

blue

", "

yellow

", "

orange

", "

white

", "

pink

", "

brown")

#如果修改元組中的元素,將返回型別錯誤資訊

colors[0] = "

black"#

錯誤資訊:typeerror: 'tuple' object does not support item assignment

持續更新......

python中常見錯誤

1.手誤造成的名字錯誤 nameerror 名字錯誤 如 nameerror name pint is not defined 2.多行 不能一行寫 syntaxerror 語法錯誤 如 syntaxerror invalid syntax 3.縮排錯誤 indentationerror unexp...

C 中常見的程式設計錯誤

1 嘗試修改字串常量 char p i m hungry p 0 s 答案與分析 上面的 能成功通過編譯,但會產生執行時的錯誤即造成記憶體的非法寫操作。i m hungry 實質上是字串常量,而常量往往被編譯器放在唯讀的記憶體區,不可寫。p初始指向這個唯讀的記憶體區,而p 0 i 則企圖去寫這個地方...

Python 中常見的錯誤型別

1.型別錯誤 typeerror must be str,notint型別錯誤 必須是字串,不能是數字.這種就是拼接的時候字串和數字混用了,應該把一方轉化為另一方2.syntaxerror invalid syntax 語法錯誤 無效的語法解決辦法就是看報錯在哪一行,從這一行往上找錯誤3.inden...