此篇文章整理新手編寫代碼常見的一些錯誤,有些錯誤是粗心的錯誤,但對于新手而已,會折騰很長時(shí)間才搞定,所以在此總結(jié)下我遇到的一些問題。希望幫助到剛?cè)腴T的朋友們。
1.NameError變量名錯誤
報(bào)錯:
>>> print aTraceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'a' is not defined
解決方案:
先要給a賦值。才能使用它。在實(shí)際編寫代碼過程中,報(bào)NameError錯誤時(shí),查看該變量是否賦值,或者是否有大小寫不一致錯誤,或者說不小心將變量名寫錯了。
注:在Python中,無需顯示變量聲明語句,變量在第一次被賦值時(shí)自動聲明。
>>> a=1>>> print a1
2.IndentationError代碼縮進(jìn)錯誤
點(diǎn)擊返回目錄
代碼:
a=1b=2if a<b:print a
報(bào)錯:
IndentationError: expected an indented block
原因:
縮進(jìn)有誤,python的縮進(jìn)非常嚴(yán)格,行首多個空格,少個空格都會報(bào)錯。這是新手常犯的一個錯誤,由于不熟悉python編碼規(guī)則。像def,class,if,for,while等代碼塊都需要縮進(jìn)。
縮進(jìn)為四個空格寬度,需要說明一點(diǎn),不同的文本編輯器中制表符(tab鍵)代表的空格寬度不一,如果代碼需要跨平臺或跨編輯器讀寫,建議不要使用制表符。
解決方案:
a=1b=2if a<b: print a
3.AttributeError對象屬性錯誤
報(bào)錯:
>>> import sys>>> sys.PathTraceback (most recent call last):File "<stdin>", line 1, in <module>AttributeError: 'module' object has no attribute 'Path'
原因:
sys模塊沒有Path屬性。
解決方案:
python對大小寫敏感,Path和path代表不同的變量。將Path改為path即可。
>>> sys.path['', '/usr/lib/python2.6/site-packages']
python知識拓展:
使用dir函數(shù)查看某個模塊的屬性
代碼如下:>>> dir(sys)
['__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']
新聞熱點(diǎn)
疑難解答
圖片精選