我有一个关于python'功能的问题'编程。
这是我的剧本:
def print_seat(seat):
for item in seat:
print "${}".format(item)
print "-"*15
total = get_seat_total(seat)
print "Total: ${}".format(total)
def get_seat_total(seat):
total = 0
for dish in seat:
total += dish
return total
def main():
seats = [[19.95], [20.45 + 3.10], [7.00/2, 2.10, 21.45], [7.00/2, 2.10, 14.99]]
grand_total = 0
for seat in seats:
print_seat(seat)
grand_total += get_seat_total(seat)
print "\n"
print "="*15
print "Grand total: ${}".format(grand_total)
if __name__ == "__main__":
main()
这是我的脚本结果:
$19.95
-----------
Total: $19.95
$23.55
-----------
Total: $23.55
$3.5
$2.1
$21.45
------------
Total: $3.5
$3.5
$2.1
$14.99
------------
Total: $3.5
============
Grand total: $50.5
但脚本的结果应如下所示:
$19.95
-----------
Total: $19.95
$23.55
-----------
Total: $23.55
$3.5
$2.1
$21.45
------------
Total: $27.05
$3.5
$2.1
$14.99
------------
Total: $20.59
============
Grand total: $91.14
从上面可以看出,列表中的总数是不同的。我想我写的一切都正确,包括列表的总和(如果我没有记错的话)。有人可以向我指出我的脚本结构有什么问题吗?或者我写错了剧本?
答案 0 :(得分:3)
问题是在你的get_seat_total()
函数中,你是从循环内部返回的,所以它只会在添加第一个项目后返回总数。您应该只在循环完成后返回,例如 -
def get_seat_total(seat):
total = 0
for dish in seat:
total += dish
return total
答案 1 :(得分:1)
我希望这有助于,
def print_seat(seat):
for item in seat:
print "${}".format(item)
print "-"*15
total = sum(seat)
print "Total: ${}".format(total)
def main():
seats = [[19.95], [20.45 + 3.10], [7.00/2, 2.10, 21.45], [7.00/2, 2.10, 14.99]]
grand_total = 0
for seat in seats:
print_seat(seat)
grand_total += sum(seat)
print "\n"
print "="*15
print "Grand total: ${}".format(grand_total)
if __name__ == "__main__":
main()
最好的,