简体   繁体   English

python变量NameError

[英]python variable NameError

I am having trouble with assigning values to vars and then accessing the values. 我在为vars分配值然后访问这些值时遇到麻烦。 For example: 例如:

# 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 returns: 追溯返回:

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

I have read up on python variables and they do not need to be declared so I am thinking they can be created and used on the fly, no? 我已经阅读了python变量,不需要声明它们,因此我认为可以即时创建和使用它们,不是吗? If so I am not quite sure what the traceback is trying to tell me. 如果是这样,我不太确定该回溯试图告诉我什么。

By the way, it appears as though python does not offer 'case' capabilities, so if anyone has any suggestions how to better offer users lists from which to choose options and assign var values I would appreciate reading them. 顺便说一句,似乎python不提供“大小写”功能,因此,如果有人对如何更好地向用户提供选择选项和分配var值的建议,我将不胜感激。 Eventually when time allows I will learn Tkinter and port to GUI. 最终,如果时间允许,我将学习Tkinter并移植到GUI。

In addition to the missing quotes around 100Mb in the last else , you also want to quote the constants in your if-statements if tSizeAns == "1": , because raw_input returns a string, which in comparison with an integer will always return false. 除了周围缺少引号100Mb的最后else ,你也想引用常量在if语句if tSizeAns == "1":因为raw_input返回一个字符串,它与整数比较将总是返回false 。

However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. 但是,缺少引号不是造成特定错误消息的原因,因为这将导致在执行之前出现语法错误。 Please check your posted code. 请检查您发布的代码。 I cannot reproduce the error message. 我无法重现该错误信息。

Also if ... elif ... else in the way you use it is basically equivalent to a case or switch in other languages and is neither less readable nor much longer. 同样, if ... elif ... else的使用方式,基本上等同于其他caseswitch ,并且可读性也不会更长。 It is fine to use here. 可以在这里使用。 One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup: 另一种方式可能是一个好主意,用,如果你只是想要分配基于另一个值的值是一个字典查找:

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

This however does only work as long as tSizeAns is guaranteed to be in the range of tSize . 然而,这仅仅只要工作tSizeAns是保证在范围tSize Otherwise you would have to either catch the KeyError exception or use a defaultdict: 否则,您将不得不捕获KeyError异常或使用defaultdict:

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

or 要么

from collections import defaultdict

[...]

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

In your case I think these methods are not justified for two values. 在您的情况下,我认为这些方法不适用于两个值。 However you could use the dictionary to construct the initial output at the same time. 但是,您可以使用字典同时构造初始输出。

Your if statements are checking for int values. 您的if语句正在检查int值。 raw_input returns a string. raw_input返回一个字符串。 Change the following line: 更改以下行:

tSizeAns = raw_input()

to

tSizeAns = int(raw_input())

This should do it: 应该这样做:

#!/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)

BTW, in case you're open to moving to Python 3.x, the differences are slight: 顺便说一句,如果您愿意使用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 HTH

Initialize tSize to 初始化tSize为

tSize = "" 

before your if block to be safe. 在您的if区块安全之前。 Also in your else case, put tSize in quotes so it is a string not an int. 同样在您的else情况下,将tSize放在引号中,以便它是字符串而不是int。 Also also you are comparing strings to ints. 另外,您还在将字符串与整数进行比较。

I would approach it like this: 我会这样处理:

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)

You could also loop until you get an acceptable answer and cover yourself in case of error: 您也可以循环播放,直到获得可接受的答案,并在出现错误的情况下掩盖自己:

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

You forgot a few quotations: 您忘记了一些报价:

# 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