Python 哨兵控制循环
我在想有没有人能帮我指点一下方向!我还是个初学者,完全搞不懂。我想做一个由哨兵控制的循环,首先让用户输入“支票金额”,然后再问“这个支票有多少顾客”。在用户输入完这些信息后,循环会一直进行,直到他们输入-1为止。
当用户输入完毕后,程序应该计算每个支票的总金额、小费和税费。对于顾客少于8人的支票,小费是18%;而顾客超过9人的支票,小费是20%。税率是8%。
最后,它还应该把所有的总金额加起来。 比如:支票1 = 100美元 支票2 = 300美元 支票3 = 20美元 所有支票总计 = 420美元 我并不是想让别人帮我做,而是希望能给我一些指引,因为我现在只完成了这些,卡住了。
目前我的代码很糟糕,根本不太能用。 我在Raptor上完成了这个程序,并且运行得很好,只是不知道怎么把它转换成Python。
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
sum5 = 0
check = 0
print ("Enter -1 when you are done")
check = int(input('Enter the amount of the check:'))
while check !=(-1):
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
tip = 0
tax = 0
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
total = check + tax + tip
sum1 = sum1 + check
sum2 = sum2 + tip
sum3 = sum3 + patron
sum4 = sum4 + tax
sum5 = sum5 + total
print ("Grand totals:")
print ("Total input check = $" + str(sum1))
print ("Total number of patrons = " + str(sum3))
print ("Total Tip = $" +str(sum2))
print ("Total Tax = $" +str(sum4))
print ("Total Bill = $" +str(sum5))
2 个回答
这个程序应该能帮助你入门。如果你需要帮助,记得查看答案下面的评论。
def main():
amounts, patrons = [], []
print('Enter a negative number when you are done.')
while True:
amount = get_int('Enter the amount of the check: ')
if amount < 0:
break
amounts.append(amount)
patrons.append(get_int('Enter the number of patrons: '))
tips, taxs = [], []
for count, (amount, patron) in enumerate(zip(amounts, patrons), 1):
tips.append(amount * (.20 if patron > 8 else .18))
taxs.append(amount * .08)
print('Event', count)
print('=' * 40)
print(' Amount:', amount)
print(' Patron:', patron)
print(' Tip: ', tips[-1])
print(' Tax: ', taxs[-1])
print()
print('Grand Totals:')
print(' Total amount:', sum(amounts))
print(' Total patron:', sum(patrons))
print(' Total tip: ', sum(tips))
print(' Total tax: ', sum(taxs))
print(' Total bill: ', sum(amounts + tips + taxs))
def get_int(prompt):
while True:
try:
return int(input(prompt))
except (ValueError, EOFError):
print('Please enter a number.')
if __name__ == '__main__':
main()
你的代码运行得不错,但逻辑上有一些问题。
看起来你打算同时处理多个检查。你可能需要用一个列表来存储这些检查和顾客,直到 check
的值变成 -1
(而且要记得不要把最后一组值加进去!)。
我觉得你真正遇到的问题是,要想退出这个循环,check
必须等于 -1
。
如果你继续往下看,你会发现你在处理 check
,而现在我们知道它是 -1
,不管之前在循环中发生了什么(每次循环 check
的值都会被覆盖)。
当你到达这些代码行时,你就会遇到真正的问题:
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
# This is the same, we know check == -1
if patron <= 8:
tip = (-1 * .18)
elif patron >= 9:
tip = (-1 * .20)
在这个时候,你可能无法对你的程序做任何有趣的事情。
编辑:再多一点帮助
这里有个关于如何将值添加到列表的例子:
checks = []
while True:
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
# here's our sentinal
if check == -1:
break
checks.append((patron, check))
print(checks)
# do something interesting with checks...
编辑:处理分币
现在你把输入解析成整数。这没问题,但如果输入是 "3.10"
,它会被截断成 3
。这可能不是你想要的结果。
使用浮点数可能是个解决办法,但也会带来其他问题。我建议在内部处理分币。你可以假设输入字符串是以美元(或欧元或其他货币)表示的。要得到分币,只需乘以 100($3.00 == 300¢
)。这样在内部你可以继续使用 int
类型。