看看Python 高手都写不出来的几个错误(一)

2021-02-09 1634

对于刚入门的 Pythonista 在学习过程中运行代码是或多或少会遇到一些错误,刚开始可能看起来比较费劲。随着代码量的积累,熟能生巧当遇到一些运行时错误时能够很快的定位问题原题。

1、

忘记在if,for,def,elif,else,class等声明末尾加:

会导致“SyntaxError :invalid syntax”如下:

1

2

if spam == 42 

print('Hello!')

2、

使用= 而不是 ==

也会导致“SyntaxError: invalid syntax”

= 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:

1

2

if spam = 42: 

print('Hello!')

3、

错误的使用缩进量

导致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”

记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:

1

2

print('Hello!')

print('Howdy!')

或者:

1

2

3

if spam == 42: 

   print('Hello!')

print('Howdy!')

4、

在 for 循环语句中忘记调用 len()

导致“TypeError: 'list' object cannot be interpreted as an integer”

通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。

该错误发生在如下代码中:

1

2

3

spam = ['cat', 'dog', 'mouse']

for i in range(spam): 

   print(spam[i])

5、

尝试修改string的值

导致“TypeError: 'str' object does not support item assignment”

string是一种不可变的数据类型,该错误发生在如下代码中:

1

2

3

spam = 'I have a pet cat.'

spam[13] = 'r'

print(spam)

而正确做法是:

1

2

3

spam = 'I have a pet cat.'

spam = spam[:13] + 'r' + spam[14:]

print(spam)

6、

尝试连接非字符串值与字符串

导致 “TypeError: Can't convert 'int' object to str implicitly”

该错误发生在如下代码中:

1

2

numEggs = 12

print('I have ' + numEggs + ' eggs.')

而正确做法是:

1

2

3

4

5

numEggs = 12

print('I have ' + str(numEggs) + ' eggs.')

 

numEggs = 12

print('I have %s eggs.' % (numEggs))

7、

在字符串首尾忘记加引号

导致“SyntaxError: EOL while scanning string literal”

该错误发生在如下代码中:

1

2

3

4

print(Hello!')

  print('Hello!)

myName = 'Al'

print('My name is ' + myName + . How are you?')

8、

变量或者函数名拼写错误

导致“NameError: name 'fooba' is not defined”

该错误发生在如下代码中:

1

2

3

4

5

foobar = 'Al'

print('My name is ' + fooba)

 

spam = ruond(4.2)

spam = Round(4.2)


相关免费学习推荐:
python教程

以上就是看看Python 高手都写不出来的几个错误(一)的详细内容,更多请关注php知识-学习天地 www.lxywzjs.com其它相关文章!

分享至:

分享到QQ空间 分享到朋友社区 新浪微博分享

栏目地图