我想知道是否有人可以帮助我指出正确的方向!我是初学者,完全迷路了。我试图做一个哨兵控制循环,要求用户"输入支票金额",然后问"有多少顾客为这张支票"。在它询问用户之后,然后输入它,直到他们输入-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))
你的代码运行良好,但你有一些逻辑问题。
看来你打算同时处理多张支票。您可能需要为此使用一个列表,并在其中添加检查和赞助人,直到 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
。可能不是你想要的。
Float可能是一个解决方案,但可能会带来其他问题。我建议在内部处理美分问题。您可以假设输入字符串是$(或€或其他形式)。要得到美分,只需乘以100 ($3.00 == 300¢
)。然后在内部你可以继续使用int
s
这个程序应该可以让你开始。如果你需要帮助,一定要在答案下面留言。
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()