我正在尝试向计算器脚本添加一些逻辑,其中我希望对一些变量进行“分组”。逻辑应该是这样的:
apples = raw_input("How many apples do you have?:")
oranges = raw_input("How many oranges do you have?:")
pears = raw_input("How many pears do you have?:")
if anyone of these three == 0:
print "So you got xx %s and xx %s" % (intthatdidntget0, int2thatdidntget0)如果这三个变量中的任何一个的值为"0",我希望在下一次计算中排除该变量。我可以对每种组合执行if/else语句,但感觉效率不是很高。
发布于 2012-12-16 19:47:15
您可以使用字典对它们进行分组:
def get_fruits(name):
response = raw_input('How many ' + name + ' do you have? ')
return int(response)
fruits = {}
for name in ['apples', 'oranges', 'pears']:
number = get_fruits(name)
if number > 0:
fruits[name] = number现在,fruits只包含数量非零的水果。
https://stackoverflow.com/questions/13900946
复制相似问题