簡體   English   中英

Python NameError

[英]Python NameError

list1 = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]

for item in list1:
    print item

不知道為什么上面的代碼會引發此錯誤:

NameError: "name 'a' is not defined"

除了正確使用引號外,請勿重新輸入字母。

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> L = list(string.ascii_lowercase)
>>> print L
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ...
>>> help(string)

您必須將字符串放入(雙引號)中

list1 = ["a","b","c",...] 

應該管用

字符串文字應使用引號引起來:)

list1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

由於可以迭代字符串,因此我會選擇並選擇以前的最佳文章。

>>> import string
>>> for letter in string.ascii_lowercase:
...     print(letter)
... 

python將列表中的成員解釋為變量,您應該將其包含在

' 要么 ”

每種語言都需要區分常量和名稱/變量。 最令人困惑的是何時必須區分字符串常量和標識符/名稱/變量。

Shell(sh,bash,ksh,csh,cmd.com等)傾向於使用常量; 因此,您只需要鍵入一個常數,然后在名稱/變量前面加上特殊字符即可($表示unix shell,%表示cmd.com等),當您需要其值時。

$ echo hello
hello
$ echo $PWD
/home/tzot
$ cd /tmp
$ cd $OLDPWD

大多數其他通用編程語言傾向於使用變量而不是使用常量,所以反之亦然:您只需鍵入變量的名稱,然后(通常)將字符串常量用引號引起來(“,”,“,[]等) :

# assumed: a_name= "the object it points to"

>>> print ("a constant")
a constant
>>> print (a_name)
the object it points to

當我需要列出字符列表時,如果std lib中定義的某些字符尚不可用,並且確實需要列表而不只是字符串,則可以使用以下形式:

punc = list(r";:`~!@#$%^&*()_-+=[]{}\|,./<?>")
vowels = list("aeiou")  # or sometimes list("aeiouy")

比所有這些多余的引號和逗號要簡單得多,讀者可以清楚地知道,我的意思是我想要一個列表,而不僅僅是一個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM