Ⅰ 我寫了一個python程序,報錯NameError: name XX is not defined 求解
Python程序,錯誤NameError:名稱XX未定義不是由聲明引起的,需要在文件的前兩行聲明代碼,聲明方法是:
1,在文件中寫一個帶有中文字元的python文件,不進行編碼。
Ⅱ python新手常見的報錯有哪些
1.NameError變數名錯誤
報錯:
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
NameError: name 'a' is not defined
解決方案:
先要給a賦值。才能使用它。在實際編寫代碼過程中,報NameError錯誤時,查看該變數是否賦值,或者是否有大小寫不一致錯誤,或者說不小心將變數名寫錯了。
註:在Python中,無需顯示變數聲明語句,變數在第一次被賦值時自動聲明。
>>> a=1
>>> print a
1
2.IndentationError代碼縮進錯誤
代碼:
a=1
b=2
if a<b:
print a
報錯:
IndentationError: expected an indented block
原因:
縮進有誤,python的縮進非常嚴格,行首多個空格,少個空格都會報錯。這是新手常犯的一個錯誤,由於不熟悉python編碼規則。像def,class,if,for,while等代碼塊都需要縮進。
縮進為四個空格寬度,需要說明一點,不同的文本編輯器中製表符(tab鍵)代表的空格寬度不一,如果代碼需要跨平台或跨編輯器讀寫,建議不要使用製表符。
解決方案:
a=1
b=2
if a<b:
print a
3.AttributeError對象屬性錯誤
報錯:
>>> import sys
>>> sys.Path
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
AttributeError: 'mole' object has no attribute 'Path'
原因:
sys模塊沒有Path屬性。
解決方案:
python對大小寫敏感,Path和path代表不同的變數。將Path改為path即可。
>>> sys.path
['', '/usr/lib/python2.6/site-packages']
python知識拓展:
使用dir函數查看某個模塊的屬性
>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_mole_names', 'byteorder', 'call_tracing', 'callstats', 'right', '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', 'moles', '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類型錯誤
4.1入參類型錯誤
代碼:
t=('a','b','c')
for i in range(t):
print a[i]
報錯:
TypeError: range() integer end argument expected, got tuple.
原因:
range()函數期望的入參是整型(integer),但卻給的入參為元組(tuple)
解決方案:
將入參元組t改為元組個數整型len(t)
將range(t)改為range(len(t))
Ⅲ Python 程序報:NameError: name 'sys' is not defined
在代碼最前面加入一行代碼:importsys。
出錯是因為沒有導入sys這個模塊。
修改後的代碼變為:
importsys
import pygame
pygame.init()
screen = pygame.display.set_mode([640,480])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
(3)nameerrorpython擴展閱讀:
Python編程常見問題
問題一,出現「name 『name』 is not defined」報錯
解決:"name"兩端是雙下劃線"_",不是只有一個""。
問題二,出現「name 'messagebox' is not defined」報錯
解決:「 」 內為某個資料庫的子mole。
在代碼中加上語句:from tkinter import messagebox,默認情況下子mole不會自動import。
問題三,出現「name 'reload' is not defined.」報錯。
解決:對於 Python 2.X添加代碼行:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
對於 Python 3.3添加代碼行:
import imp
imp.reload(sys)