简体   繁体   中英

how to only accept two user inputs, and break loop using one of the inputs

I am trying to ask the user 'would you like to add another store' by giving them a yes(y) or no(n) option, however, I don't know how to loop the code back once an error message has been thrown. I am trying to make it so that only 'y' and 'n' are enterable in the inputs or throw an error message.

import copy

All_Store_Daily_income = []  # this becomes 2D list
days_of_the_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
is_last_weekday = None


def get_daily_store_data():
    Copy_of_store_data = []  # create a list
    Day_Counter = 0
    while Day_Counter < 7:
        try:
            Daily_sales = float(input(f"What is the income for {days_of_the_week[Day_Counter]}? "))
            Copy_of_store_data.append(Daily_sales)  # fill list with store data
            Day_Counter = Day_Counter + 1
            global is_last_weekday
            is_last_weekday = Day_Counter == 7
        except ValueError:
            print("Please enter a integer or float, no letters allowed!")
    return Copy_of_store_data # return list

def store_adder_programme():
global Store_name_list
global number_of_stores
Store_name_list = []
number_of_stores = 1
Adding_stores = 'y'

while Adding_stores == 'y':
    store_name = input("What is the name of your registered store? ")
    Store_name_list.append(store_name)
    store_data = get_daily_store_data() # get list from function return value
    All_Store_Daily_income.append(store_data)  # append returned list to 
    All_Store_Daily_income
    print(Store_name_list)
        
    if is_last_weekday and Adding_stores == 'y':            
        print(All_Store_Daily_income)# prints the 2D list 
        print('Would you like to add a new store?')
        Adding_stores = input("If YES(y), If NO(n): ")                             
        number_of_stores = number_of_stores + 1                   
        
store_adder_programme()

I would try to write something like this.

def need_another_store():
    correct_answers = ['y', 'n']
    print('Would you like to add a new store?')

    while True:
        answer = input("If YES(y), If NO(n): ")

        if answer not in correct_answers:
            print("Please enter 'y' or 'n'")
        else:
            return answer

if is_last_weekday and Adding_stores == 'y':
    Adding_stores = need_another_store()
    number_of_stores = number_of_stores + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM