新手常見(jiàn)6種的python報(bào)錯(cuò)及解決方法
此篇文章整理新手編寫(xiě)代碼常見(jiàn)的一些錯(cuò)誤,有些錯(cuò)誤是粗心的錯(cuò)誤,但對(duì)于新手而已,會(huì)折騰很長(zhǎng)時(shí)間才搞定,所以在此總結(jié)下我遇到的一些問(wèn)題。希望幫助到剛?cè)腴T(mén)的朋友們。
1.NameError變量名錯(cuò)誤
報(bào)錯(cuò):
>>> print a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined
解決方案:
先要給a賦值。才能使用它。在實(shí)際編寫(xiě)代碼過(guò)程中,報(bào)NameError錯(cuò)誤時(shí),查看該變量是否賦值,或者是否有大小寫(xiě)不一致錯(cuò)誤,或者說(shuō)不小心將變量名寫(xiě)錯(cuò)了。
注:在Python中,無(wú)需顯示變量聲明語(yǔ)句,變量在第一次被賦值時(shí)自動(dòng)聲明。
>>> a=1 >>> print a 1
2.IndentationError代碼縮進(jìn)錯(cuò)誤
點(diǎn)擊返回目錄
代碼:
a=1 b=2 if a<b: print a
報(bào)錯(cuò):
IndentationError: expected an indented block
原因:
縮進(jìn)有誤,python的縮進(jìn)非常嚴(yán)格,行首多個(gè)空格,少個(gè)空格都會(huì)報(bào)錯(cuò)。這是新手常犯的一個(gè)錯(cuò)誤,由于不熟悉python編碼規(guī)則。像def,class,if,for,while等代碼塊都需要縮進(jìn)。
縮進(jìn)為四個(gè)空格寬度,需要說(shuō)明一點(diǎn),不同的文本編輯器中制表符(tab鍵)代表的空格寬度不一,如果代碼需要跨平臺(tái)或跨編輯器讀寫(xiě),建議不要使用制表符。
解決方案:
a=1 b=2 if a<b: print a
3.AttributeError對(duì)象屬性錯(cuò)誤
報(bào)錯(cuò):
>>> import sys >>> sys.Path Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Path'
原因:
sys模塊沒(méi)有Path屬性。
解決方案:
python對(duì)大小寫(xiě)敏感,Path和path代表不同的變量。將Path改為path即可。
>>> sys.path ['', '/usr/lib/python2.6/site-packages']
python知識(shí)拓展:
使用dir函數(shù)查看某個(gè)模塊的屬性
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
4.TypeError類型錯(cuò)誤
4.1入?yún)㈩愋湾e(cuò)誤
代碼:
t=('a','b','c')
for i in range(t):
print a[i]
報(bào)錯(cuò):
TypeError: range() integer end argument expected, got tuple.
原因:
range()函數(shù)期望的入?yún)⑹钦停╥nteger),但卻給的入?yún)樵M(tuple)
解決方案:
將入?yún)⒃Mt改為元組個(gè)數(shù)整型len(t)
將range(t)改為range(len(t))
4.2入?yún)€(gè)數(shù)錯(cuò)誤
4.2.1關(guān)于元組作為入?yún)?/p>
代碼:
# coding=utf-8
'''
Created on 2016-7-21
@author: Jennifer
Project:顯式等待
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import ctime
driver=webdriver.Firefox()
driver.get(r'http://www.baidu.com/')
loc=(By.ID,'kw')
print ctime()
element=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(*loc))
element.send_keys('selenium')
print ctime()
driver.quit()
報(bào)錯(cuò):
Traceback (most recent call last): File "D:\system files\workspace\selenium\autotestcombat\test_4_7_1_webdriverwait.py", line 18, in <module> element=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(*loc)) TypeError: __init__() takes exactly 2 arguments (3 given)
原因:
類的函數(shù)__init__()需要兩個(gè)參數(shù),但實(shí)際上給了三個(gè)。
EC.visibility_of_element_located類的入?yún)?yīng)該是兩個(gè)入?yún)ⅲ?self和元組。但卻給了三個(gè)參數(shù) self和*loc中的兩個(gè)元素作為入?yún)ⅰ?br />
解決方案:
這里要將EC.visibility_of_element_located(*loc)改為EC.visibility_of_element_located(loc),入?yún)樵M,而不是元組里邊的兩個(gè)值。
python知識(shí)拓展:
關(guān)于入?yún)?的用法
以元組作為函數(shù)入?yún)ⅲ绻M前加*號(hào),說(shuō)明傳遞的入?yún)樵M中的各個(gè)元素。如果元組前沒(méi)有加*號(hào),說(shuō)明傳遞的入?yún)樵M本身。
舉例說(shuō)明:
loc =(By.NAME,'email')
element1=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(loc)) #只要一個(gè)參數(shù)(不考慮self情況下),元組loc,即:(By.NAME,'email')。 直接傳loc。
element2=driver.find_element(*loc)#需要兩個(gè)參數(shù),元組loc的元素,即:By.NAME,'email'。直接傳*loc
4.2.2其他
報(bào)錯(cuò):
>>> import os >>> os.listdir() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: listdir() takes exactly 1 argument (0 given)
原因:
listdir()函數(shù)需要一個(gè)入?yún)?,但是只給了0個(gè)入?yún)ⅰ?/p>
解決方案:
加一個(gè)入?yún)?/p>
>>> os.listdir('/home/autotest')
['hello.py', 'email126pro']
python知識(shí)拓展:
如何查看某個(gè)函數(shù)的使用,可以使用help查看。
>>> help(os.listdir) Help on built-in function listdir in module posix: listdir(...) listdir(path) -> list_of_strings Return a list containing the names of the entries in the directory. path: path of directory to list
說(shuō)明:os.listdir()函數(shù)需要一個(gè)path路徑入?yún)?,函?shù)結(jié)果返回值是由字符串組成的列表。
4.3非函數(shù)卻以函數(shù)來(lái)調(diào)用
報(bào)錯(cuò):
>>> t=('a','b','c')
>>> t()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
原因:
t為元組,元組不能被調(diào)用,不能加()。初學(xué)者編寫(xiě)代碼時(shí),偶爾粗心會(huì)將變量當(dāng)做方法來(lái)調(diào)用(不小心加了括號(hào))。所以要認(rèn)真檢查下是否變量加了括號(hào),或者方法漏加了括號(hào)。
解決方案:
將括號(hào)去除。
>>> t
('a', 'b', 'c')
5.IOError輸入輸出錯(cuò)誤
5.1文件不存在報(bào)錯(cuò)
報(bào)錯(cuò):
>>> f=open("Hello.py")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'Hello.py'
原因:
open()函數(shù)沒(méi)有指明mode,默認(rèn)為只讀方式,如果該目錄下沒(méi)有Hello.py的文件,則會(huì)報(bào)錯(cuò),可查看是否拼寫(xiě)有錯(cuò)誤,或者是否大小寫(xiě)錯(cuò)誤,或者根本不存在這個(gè)文件。
解決方案:
該目錄下有hello.py文件,打開(kāi)該文件即可。
>>> f=open("hello.py")
python知識(shí)拓展:
如何查看python解釋器當(dāng)前路徑:
>>> import os
>>> os.getcwd()
'/home/autotest'
查看python解釋器當(dāng)前路徑下有哪些文件:
>>> os.listdir('/home/autotest')
['hello.py', 'email126pro']
5.2因文件權(quán)限問(wèn)題報(bào)錯(cuò)
報(bào)錯(cuò):
>>> f=open("hello.py")
>>> f.write("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for writing
原因:
open("hello.py")如果入?yún)](méi)有加讀寫(xiě)模式參數(shù)mode,說(shuō)明默認(rèn)打開(kāi)文件的方式為只讀方式,而此時(shí)又要寫(xiě)入字符,所以權(quán)限受限,才會(huì)報(bào)錯(cuò)。
解決方案:
更改模式
>>> f=open("hello.py",'w+')
>>> f.write("test")
6.KeyError字典鍵值錯(cuò)誤
報(bào)錯(cuò):
常見(jiàn)報(bào)錯(cuò)有,測(cè)試一接口,接口返回?cái)?shù)據(jù)一般是json格式,而測(cè)試該接口校驗(yàn)?zāi)硞€(gè)值是否正確,如果key拼寫(xiě)錯(cuò)了,就會(huì)報(bào)KeyError。簡(jiǎn)單舉例如下:
>>> d={'a':1,'b':2,'c':3}
>>> print d['a']
1
>>> print d['f']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'
解決方案:
訪問(wèn)d中有的鍵值,如a,b或c。
推薦書(shū)單:
你眼中的Python大牛 應(yīng)該都有這份書(shū)單
不可錯(cuò)過(guò)的十本Python好書(shū)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
PyTorch和Keras計(jì)算模型參數(shù)的例子
今天小編就為大家分享一篇PyTorch和Keras計(jì)算模型參數(shù)的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
pycharm運(yùn)行出現(xiàn)ImportError:No module named的解決方法
今天小編就為大家分享一篇pycharm運(yùn)行出現(xiàn)ImportError:No module named的解決方法。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
python 兩個(gè)一樣的字符串用==結(jié)果為false問(wèn)題的解決
這篇文章主要介紹了python 兩個(gè)一樣的字符串用==結(jié)果為false問(wèn)題的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
11個(gè)Python3字典內(nèi)置方法大全與示例匯總
這篇文章主要給大家介紹了11個(gè)Python3字典內(nèi)置方法大全與示例的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
python實(shí)現(xiàn)AdaBoost算法的示例
這篇文章主要介紹了python實(shí)現(xiàn)AdaBoost算法的示例,幫助大家更好的理解和了解機(jī)器學(xué)習(xí)算法,感興趣的朋友可以了解下2020-10-10
Django 解決阿里云部署同步數(shù)據(jù)庫(kù)報(bào)錯(cuò)的問(wèn)題
這篇文章主要介紹了Django 解決阿里云部署同步數(shù)據(jù)庫(kù)報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
Python中sorted()排序與字母大小寫(xiě)的問(wèn)題
這篇文章主要介紹了Python中sorted()排序與字母大小寫(xiě)的問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
對(duì)python抓取需要登錄網(wǎng)站數(shù)據(jù)的方法詳解
今天小編就為大家分享一篇對(duì)python抓取需要登錄網(wǎng)站數(shù)據(jù)的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Django websocket原理及功能實(shí)現(xiàn)代碼
這篇文章主要介紹了Django websocket原理及功能實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11

