我很难将值赋值给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似乎没有提供“case”功能,所以如果有人有任何建议,如何更好地向用户提供选择选项和分配var值的列表,我将非常感激地阅读它们。最后,当时间允许时,我将学习Tkinter并移植到GUI。
发布于 2013-12-31 23:25:12
您的if语句正在检查int值。raw_input返回一个字符串。更改以下行:
tSizeAns = raw_input()至
tSizeAns = int(raw_input())发布于 2013-12-31 23:26:07
除了上次100Mb中缺少的引号外,还需要引用if语句if tSizeAns == "1":中的常量,因为raw_input返回字符串,与整数相比,字符串总是返回false。
但是,缺少的引号并不是特定错误消息的原因,因为它会在执行之前导致语法错误。请检查您的张贴代码。我无法复制错误消息。
而且,在您使用if ... elif ... else的方式上,它基本上等同于其他语言中的case或switch,它既不降低可读性,也不长得多。这里可以用。如果您只想根据另一个值分配一个值,另一种可能是使用的方法是字典查找:
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]在您的例子中,我认为这些方法对于两个值是不合理的。但是,您可以使用字典同时构造初始输出。
发布于 2013-12-31 23:29:06
这应该可以做到:
#!/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)顺便说一句,如果您愿意使用Python3.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
https://stackoverflow.com/questions/20864135
复制相似问题