Python组变量

时间:2012-12-16 11:43:00

标签: python

我正在尝试在计算器脚本中添加一些逻辑,我想在其中“分组”一些变量。逻辑将是这样的:

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语句,但感觉效率不高。

1 个答案:

答案 0 :(得分:5)

您可以使用字典对它们进行分组:

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仅包含非零数量的水果。