1

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

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 语句,但这感觉不是很有效。

4

1 回答 1

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

于 2012-12-16T11:47:15.167 回答