我有一个关于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
从上面可以看出,列表中的总数是不同的。我想我写的所有内容都是正确的,包括列表的总和(如果我没记错的话)。有人能指出我是什么问题与我的脚本结构?还是我写错了剧本?
问题是,在您的get_seat_total()
函数中,您从循环内部返回,因此它将在仅添加第一项后返回总数。你应该只在循环完成后返回,示例-
def get_seat_total(seat):
total = 0
for dish in seat:
total += dish
return total
我希望这对你有帮助,
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()
,