Reputation: 53
Problem: Write a program that will allow a grocery store to keep track of the total number of bottles collected for recycling for seven days. The program should allow the user to enter the number of bottles returned for each of the seven days. The program will calculate the total number of bottles returned for the week and the amount paid out (the total returned times 10 cents.) The output of the program should include the total number of bottles returned and the total paid out.
My problem is that I need to add input validation within a counter while loop. For ex: if the user enters a number less than 0, my code needs to writes "Input cannot be less than 0" and then it will continue with the code. How can I do this?
This is my code:
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)
I've tried many things, such as modifying my code to make it loop like this, but it didn't work. I'm not sure how to structure an input validation. Please help.
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)
Upvotes: 0
Views: 263
Reputation: 2434
if the user enters a number less than 0, my code needs to writs "Input cannot be less than 0" and then it will continue with the code. How can I do this?
You can just add a verification and use the continue
statement:
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
Upvotes: 1