簡體   English   中英

python變量NameError

[英]python variable NameError

我在為vars分配值然后訪問這些值時遇到麻煩。 例如:

# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"

tSizeAns = raw_input()

if tSizeAns == 1:
    tSize = "100Mb"
elif tSizeAns == 2:
    tSize = "250Mb"
else:
    tSize = 100Mb    # in case user fails to enter either a 1 or 2

print "\nYou  want to create a random song list that is " + tSize + "."

追溯返回:

Traceback (most recent call last):
  File "./ranSongList.py", line 87, in <module>
    print "\nYou  want to create a random song list that is " + tSize + "."
NameError: name 'tSize' is not defined

我已經閱讀了python變量,不需要聲明它們,因此我認為可以即時創建和使用它們,不是嗎? 如果是這樣,我不太確定該回溯試圖告訴我什么。

順便說一句,似乎python不提供“大小寫”功能,因此,如果有人對如何更好地向用戶提供選擇選項和分配var值的建議,我將不勝感激。 最終,如果時間允許,我將學習Tkinter並移植到GUI。

除了周圍缺少引號100Mb的最后else ,你也想引用常量在if語句if tSizeAns == "1":因為raw_input返回一個字符串,它與整數比較將總是返回false 。

但是,缺少引號不是造成特定錯誤消息的原因,因為這將導致在執行之前出現語法錯誤。 請檢查您發布的代碼。 我無法重現該錯誤信息。

同樣, if ... elif ... else的使用方式,基本上等同於其他caseswitch ,並且可讀性也不會更長。 可以在這里使用。 另一種方式可能是一個好主意,用,如果你只是想要分配基於另一個值的值是一個字典查找:

tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]

然而,這僅僅只要工作tSizeAns是保證在范圍tSize 否則,您將不得不捕獲KeyError異常或使用defaultdict:

lookup = {"1": "100Mb", "2": "200Mb"}
try:
    tSize = lookup[tSizeAns]
except KeyError:
    tSize = "100Mb"

要么

from collections import defaultdict

[...]

lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"})
tSize = lookup[tSizeAns]

在您的情況下,我認為這些方法不適用於兩個值。 但是,您可以使用字典同時構造初始輸出。

您的if語句正在檢查int值。 raw_input返回一個字符串。 更改以下行:

tSizeAns = raw_input()

tSizeAns = int(raw_input())

應該這樣做:

#!/usr/local/cpython-2.7/bin/python

# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"

tSizeAns = int(raw_input())

if tSizeAns == 1:
    tSize = "100Mb"
elif tSizeAns == 2:
    tSize = "250Mb"
else:
    tSize = "100Mb"    # in case user fails to enter either a 1 or 2

print "\nYou  want to create a random song list that is {}.".format(tSize)

順便說一句,如果您願意使用Python 3.x,則區別很小:

#!/usr/local/cpython-3.3/bin/python

# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print("\nHow much space should the random song list occupy?\n")
print("1. 100Mb")
print("2. 250Mb\n")

tSizeAns = int(input())

if tSizeAns == 1:
    tSize = "100Mb"
elif tSizeAns == 2:
    tSize = "250Mb"
else:
    tSize = "100Mb"    # in case user fails to enter either a 1 or 2

print("\nYou want to create a random song list that is {}.".format(tSize))

HTH

初始化tSize為

tSize = "" 

在您的if區塊安全之前。 同樣在您的else情況下,將tSize放在引號中,以便它是字符串而不是int。 另外,您還在將字符串與整數進行比較。

我會這樣處理:

sizes = [100, 250]
print "How much space should the random song list occupy?"
print '\n'.join("{0}. {1}Mb".format(n, s)
                for n, s in enumerate(sizes, 1)) # present choices
choice = int(raw_input("Enter choice:")) # throws error if not int
size = sizes[0] # safe starting choice
if choice in range(2, len(sizes) + 1):
    size = sizes[choice - 1] # note index offset from choice
print "You  want to create a random song list that is {0}Mb.".format(size)

您也可以循環播放,直到獲得可接受的答案,並在出現錯誤的情況下掩蓋自己:

choice = 0
while choice not in range(1, len(sizes) + 1): # loop
    try: # guard against error
        choice = int(raw_input(...))
    except ValueError: # couldn't make an int
        print "Please enter a number"
        choice = 0
size = sizes[choice - 1] # now definitely valid

您忘記了一些報價:

# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"

tSizeAns = raw_input()

if tSizeAns == "1":
    tSize = "100Mb"
elif tSizeAns == "2":
    tSize = "250Mb"
else:
    tSize = "100Mb"    # in case user fails to enter either a 1 or 2

print "\nYou  want to create a random song list that is " + tSize + "."

暫無
暫無

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

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