在Python中使用for循环进行迭代

jas*_*son -1 python for-loop

任何人都可以帮助理解为什么computeBill函数中的循环不迭代?

groceries = ["banana", "orange","apple"]

stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}

def computeBill(food):
    total = 0.0
    for item in food:
        total += prices[str(item)] + stock[str(item)]
        print total
        return total

computeBill(groceries)
Run Code Online (Sandbox Code Playgroud)

eld*_*his 6

你打电话return 里面,因为它当前缩进的循环,因此它的第一个迭代后执行.可能你想将它移到循环之外(与for自身相同的缩进级别),因此在迭代完成后调用它:

def computeBill(food):
    total = 0.0
    for item in food:
        total += prices[str(item)] + stock[str(item)]
        print total

    return total
Run Code Online (Sandbox Code Playgroud)