Python 之 编程中常见错误

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

 

 

持续更新......

posted @ 2018-12-19 22:19  云里飞  阅读(349)  评论(0编辑  收藏  举报