当前位置: 移动技术网 > IT编程>脚本编程>Python > 17个新手常见错误,送给初学Python的你!

17个新手常见错误,送给初学Python的你!

2020年04月07日  | 移动技术网IT编程  | 我要评论

计秋君,中国保健品排行榜,金四胖 金五胖

当初学 python 时,想要弄懂 python 的错误信息的含义可能有点复杂。这里列出了常见的的一些让你程序 crash 的运行时错误。

1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :(导致 “syntaxerror :invalid syntax”)

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

if spam == 42
    print('hello!')

2)使用 = 而不是 ==(导致“syntaxerror: invalid syntax”)

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

if spam = 42:
    print('hello!')

3)错误的使用缩进量。(导致“indentationerror:unexpected indent”、“indentationerror:unindent does not match any outer indetation level”以及“indentationerror:expected an indented block”)

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

print('hello!')
    print('howdy!')

或者:

if spam == 42:
    print('hello!')
  print('howdy!')

或者:

if spam == 42:
print('hello!')

4)在 for 循环语句中忘记调用 len() (导致“typeerror: 'list' object cannot be interpreted as an integer”)

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

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

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
    print(spam[i])

5)尝试修改string的值(导致“typeerror: 'str' object does not support item assignment”)

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

spam = 'i have a pet cat.'
spam[13] = 'r'
print(spam)

而你实际想要这样做:

spam = 'i have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)

6)尝试连接非字符串值与字符串(导致 “typeerror: can't convert 'int' object to str implicitly”)

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

numeggs = 12
print('i have ' + numeggs + ' eggs.')

而你实际想要这样做:

numeggs = 12
print('i have ' + str(numeggs) + ' eggs.')

或者:

numeggs = 12
print('i have %s eggs.' % (numeggs))

7)在字符串首尾忘记加引号(导致“syntaxerror: eol while scanning string literal”)

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

print(hello!')

或者:

print('hello!)

或者:

myname = 'al'
print('my name is ' + myname + . how are you?')

8)变量或者函数名拼写错误(导致“nameerror: name 'fooba' is not defined”)

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

foobar = 'al'
print('my name is ' + fooba)

或者:

spam = ruond(4.2)

或者:

spam = round(4.2)

9)方法名拼写错误(导致 “attributeerror: 'str' object has no attribute 'lowerr'”)

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

spam = 'this is in lowercase.'
spam = spam.lowerr()

10)引用超过list最大索引(导致“indexerror: list index out of range”)

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

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11)使用不存在的字典键值(导致“keyerror:‘spam’”)

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

spam = {'cat': 'zophie', 'dog': 'basil', 'mouse': 'whiskers'}
print('the name of my pet zebra is ' + spam['zebra'])

12)尝试使用python关键字作为变量名(导致“syntaxerror:invalid syntax”)

python关键不能用作变量名,该错误发生在如下代码中:

class = 'algebra'

python3的关键字有:and, as, assert, break, class, continue, def, del, elif, else, except, false, finally, for, from, global, if, import, in, is, lambda, none, nonlocal, not, or, pass, raise, return, true, try, while, with, yield

13)在一个定义新变量中使用增值操作符(导致“nameerror: name 'foobar' is not defined”)

不要在声明变量时使用0或者空字符串作为初始值,这样使用自增操作符的一句spam += 1等于spam = spam + 1,这意味着spam需要指定一个有效的初始值。

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

spam = 0
spam += 42
eggs += 42

14)在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“unboundlocalerror: local variable 'foobar' referenced before assignment”)

在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。

这意味着你不能在定义它之前把它当全局变量在函数中使用。

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

somevar = 42
def myfunction():
    print(somevar)
    somevar = 100
myfunction()

15)尝试使用 range()创建整数列表(导致“typeerror: 'range' object does not support item assignment”)

有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。

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

spam = range(10)
spam[4] = -1

也许这才是你想做:

spam = list(range(10))
spam[4] = -1

(注意:在 python 2 中 spam = range(10) 是能行的,因为在 python 2 中 range() 返回的是list值,但是在 python 3 中就会产生以上错误)

16)不错在 ++ 或者 -- 自增自减操作符。(导致“syntaxerror: invalid syntax”)

如果你习惯于例如 c++ , java , php 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在python中是没有这样的操作符的。

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

spam = 1
spam++

也许这才是你想做的:

spam = 1
spam += 1

17)忘记为方法的第一个参数添加self参数(导致“typeerror: mymethod() takes no arguments (1 given)”)

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

class foo():
    def mymethod():
        print('hello!')
a = foo()
a.mymethod()

在学习python的过程中,很多小伙伴往往因为没有资料或者没人指导从而导致自己不想学下去了,因此我特意准备了大量的pdf书籍、视频教程,在这个裙里592加上539再加上176都免费送给大家!不管你是零基础还是有基础都可以获取到自己相对应的学习礼包!包括python软件工具和2019最新入门到实战教程

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网