2017-05-03 185 views
0

我正在通过CodeAcademy的初学者Python课程进行工作。这是其中一项练习的一部分,您在杂货店“检查”,但我想要代码打印最终账单/“总计”而不是仅返回“总计”。我不明白为什么它不打印。我已经尝试在迭代之后将它放在最后,并且在这里,在递归中(在返回总数之前),以查看它是否会在每一步之后进行打印。当我运行这个代码时,没有任何显示。为什么我不能在函数内打印结果?

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

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

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


food = shopping_list 

def compute_bill(food): 
    total = 0 
    for item in food: 
     if stock[item]>0: 
      total += prices[item] 

      stock[item] -=1 
    print total 
    return total 

编辑: 这些也没有给我读出:

def compute_bill(food): 
    total = 0 
    for item in food: 
    if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 
    print "Total is $",total #tried 0-5 indentations, same blank result 

然而

def compute_bill(food): 
    total = 0 
    for item in food: 
    if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 
    print "Total is $",total #tried 0-5 indentations, same blank result 
    return total 

print compute_bill(food) 

返回

Total is $ 5.5 
5.5 

虽然 - 我没有找到一个解决方案...

def compute_bill(food): 
    total = 0 
    for item in food: 
    if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 

    return total 

print "Total is $",compute_bill(food) 

返回 总计为$ 5.5 ......但我很困惑,为什么我不能只是打印总变量,它应该已被更新。它为什么在那里工作,但不是作为功能的饲料。这只是一个练习中的问题,但我无法弄清楚为什么这样做。

回答

1

在你的第一个例子,

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

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

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


food = shopping_list 

def compute_bill(food): 
    total = 0 
    for item in food: 
     if stock[item]>0: 
      total += prices[item] 

      stock[item] -=1 
    print total 
    return total 

定义功能def compute_bill。你永远不会调用这个函数。该函数在被调用时被执行,例如, compute_bill(["banana"])

+0

谢谢!这在教程中没有明确说明,因为它们似乎主要是让我们在不调用它们的情况下创建函数。 – toonarmycaptain

1

我不知道我很明白的问题,但你说

但我很困惑,为什么我不能只是打印总变量,它应该已被更新。

如果你试图从它不会工作之外的功能打印total,因为total变量只在函数内部声明。当你return total你允许你的其他代码从你的函数外部获取数据,这就是为什么print computeBill(food)确实工作。

编辑,如果你还希望在每次迭代打印总,您的代码:

def compute_bill(food): 
    total = 0 
    for item in food: 
    if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 
     print "Total is $",total 

肯定应该有这个缺口,这意味着你将打印每次在for循环迭代时间(如果你保持原样,它只会在for之后打印)。

1

print语句是函数compute_bill(..)的一部分,除非调用函数compute_bill(..),否则它将不会执行。

def compute_bill(food): 
    total = 0 
    for item in food: 
     if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 
    print "Total is $",total #this works 

compute_bill(food) # call the function it has the print statement 
相关问题