如何在python代码中使用计数器while循环中的输入验证?



问题:编写一个程序,让杂货店记录七天内回收的瓶子总数。该程序应该允许用户输入七天内每天退回的瓶子数量。该程序将计算一周退回的瓶子总数和支付的金额(退回的总数乘以10美分)。程序的输出应包括退回的瓶子总数和支付的总数。

我的问题是我需要在计数器while循环中添加输入验证。例如:如果用户输入一个小于0的数字,我的代码需要写&;Input不能小于0&;然后它会继续执行代码。我该怎么做呢?

这是我的代码:

totalBottles = 0
todayBottles = 0
totalPayout = 0
counter = 1
eachBottle = float(.10)
while counter <= 7:
print ('Enter the number of bottles for today: ')
todayBottles = int(input())
totalBottles = totalBottles + todayBottles
counter = counter + 1
totalPayout = eachBottle * totalBottles
print ('The amount of bottles collected for the week are', totalBottles)
print ('The payout total for the week is $', totalPayout)

我尝试了很多方法,比如修改我的代码使它像这样循环,但它不起作用。我不确定如何构建输入验证。请帮助。

totalBottles = 0
todayBottles = 0
totalPayout = 0
counter = 1
eachBottle = float(.10)
def main():
answer = 'yes'
while answer == 'yes' or answer == 'Yes':
calculate_total()
answer = input('Do you want to enter next week? (enter "yes" or "no" directly as displayed): ')
print_statements()

def calculate_total():
todayBottles = int(input('Enter todays bottles'))
while todayBottles < 0:
print ('ERROR: the amount cannot be nagative. ')
while counter <= 7:
todayBottles = int(input('Enter todays bottles '))
totalBottles = totalBottles + todayBottles
counter = counter + 1
totalPayout = eachBottle * totalBottles
def print_statements():
print ('The amount of bottles collected for the week are', totalBottles)
print ('The payout total for the week is $', totalPayout)

如果用户输入的数字小于0,我的代码需要写" Input不能小于0 ";然后它会继续执行代码。我该怎么做呢?

您可以添加一个验证并使用continue语句:

while counter <= 7:
print ('Enter the number of bottles for today: ')
todayBottles = int(input())
if todayBottles < 0:
print('Value not allowed, must be >= 0')
continue
totalBottles = totalBottles + todayBottles
counter = counter + 1
totalPayout = eachBottle * totalBottles

最新更新