python中常见的谬误:
0、遗记写冒号
正在 if、elif、else、for、while、class、def 语句前面遗记增加 “:”
if spam == 42 print('Hello!')
招致:SyntaxError: invalid syntax
二、应用谬误的缩进
Python用缩进区别代码块,常见的谬误用法:
print('Hello!') print('Howdy!')
招致:IndentationError: unexpected indent。同一个代码块中的每一行代码都必需放弃分歧的缩进量
if spam == 42: print('Hello!') print('Howdy!')
招致:IndentationError: unindent does not match any outer indentation level。代码块完结之后缩进规复到原来的地位
if spam == 42: print('Hello!')
招致:IndentationError: expected an indented block,“:” 前面要应用缩进
三、变量不界说
if spam == 42: print('Hello!')
招致:NameError: name 'spam' is not defined
四、猎取列表元素索引地位遗记挪用 len 办法
经过索引地位猎取元素的时分,遗记应用 len 函数猎取列表的长度。
spam = ['cat', 'dog', 'mouse'] for i in range(spam): print(spam[i])
招致:TypeError: range() integer end argument expected, got list.
正确的做法是:
spam = ['cat', 'dog', 'mouse'] for i in range(len(spam)): print(spam[i])
当然,更 Pythonic 的写法是用 enumerate
spam = ['cat', 'dog', 'mouse'] for i, item in enumerate(spam): print(i, item)
五、修正字符串
字符串一个序列工具,支持用索引猎取元素,但它以及列表工具没有同,字符串是不成变工具,没有支持修正。
spam = 'I have a pet cat.' spam[13] = 'r' print(spam)
招致:TypeError: 'str' object does not support item assignment
正确地做法应该是:
spam = 'I have a pet cat.' spam = spam[:13] + 'r' + spam[14:] print(spam)
六、字符串与非字符串联接
num_eggs = 12 print('I have ' + num_eggs + ' eggs.')
招致:TypeError: cannot concatenate 'str' and 'int' objects
字符串与非字符串联接时,必需把非字符串工具强迫转换为字符串类型
num_eggs = 12 print('I have ' + str(num_eggs) + ' eggs.')
或许应用字符串的格局化方式
num_eggs = 12 print('I have %s eggs.' % (num_eggs))
七、应用谬误的索引地位
spam = ['cat', 'dog', 'mouse'] print(spam[3])
招致:IndexError: list index out of range
列表工具的索引是从0开端的,第3个元素应该是应用 spam[2] 拜访
八、字典中应用没有存正在的键
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'} print('The name of my pet zebra is ' + spam['zebra'])
正在字典工具中拜访 key 能够应用 [],然而假如该 key 没有存正在,就会招致:KeyError: 'zebra'
正确的形式应该应用 get 办法
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'} print('The name of my pet zebra is ' + spam.get('zebra'))
key 没有存正在时,get 默许前往 None
九、用要害字做变量名
class = 'algebra'
招致:SyntaxError: invalid syntax
正在 Python 中没有容许应用要害字作为变量名。Python3 一共有33个要害字。
>>> import keyword >>> print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
十、函数中部分变量赋值前被应用
someVar = 42 def myFunction(): print(someVar) someVar = 100 myFunction()
招致:UnboundLocalError: local variable 'someVar' referenced before assignment
当函数中有一个与全局作用域中同名的变量时,它会依照 LEGB 的程序查找该变量,假如正在函数外部的部分作用域中也界说了一个同名的变量,那末就再也不到内部作用域查找了。
因而,正在 myFunction 函数中 someVar 被界说了,以是 print(someVar) 就再也不里面查找了,然而 print 的时分该变量还没赋值,以是呈现了 UnboundLocalError
十一、应用自增 “++” 自减 “--”
spam = 0 spam++
哈哈,Python 中不自增自减操作符,假如你是从C、Java转过去的话,你可要留意了。你能够应用 “+=” 来代替 “++”
spam = 0 spam += 1
十二、谬误地挪用类中的办法
class Foo: def method1(): print('m1') def method2(self): print("m2") a = Foo() a.method1()
招致:TypeError: method1() takes 0 positional arguments but 1 was given
method1 是 Foo 类的一个成员办法,该办法没有承受任何参数,挪用 a.method1() 相称于挪用 Foo.method1(a),但 method1 没有承受任何参数,以是报错了。正确的挪用形式应该是 Foo.method1()。
更多相干常识请存眷python视频教程栏目
以上就是python中一些常见的谬误的具体内容,更多请存眷资源魔其它相干文章!
标签: Python python教程 python编程 python使用问题
抱歉,评论功能暂时关闭!