0

I am looking to write code that takes an input and looks for y or n. I am having a problem filtering out things that are not y or n and if the input is incorrect, that it goes and asks for the input again.

Here are a couple things I've tried:

while True:
    try:
        need_a_classlist = int(input("\nDo we need to make a classlist first? Y/N "))
    except ValueError or str(need_a_classlist).lower != ("y", "n"):
        print("\nOkay, let's make a classlist!")
        break
    else:
        print("\nInvalid Response, please type 'y' or 'n'.")
        continue

and:

if need_a_classlist == "y":
    def add_new_student(student):
        class_list.append(student)
        return class_list
    #get a number for a classlist
    number_of_students = int(input("\nHow many students in the class? "))
    #user input to add to class list
    while number_of_students > 0:
        new_student_name = input("\nWhat is the students name?  ").lower()
        if new_student_name.isalpha():
            add_new_student(new_student_name)
            print( "\n" + new_student_name.title() + " added to class list!")
            number_of_students -= 1
        if number_of_students == 0:
            break
#If they say no
elif need_a_classlist == "n":
    print("\nOkay let's move on to the seating chart.")
#If they put in something else
else:
    print("\nInvalid entry, please try again.")

but this does not repeat.

halfer
  • 19,824
  • 17
  • 99
  • 186
z.mcg
  • 1
  • 2
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Mr. T Feb 21 '18 at 19:38

1 Answers1

1

This should work for you:

done = False
while not done:
    inp = input("Do we need to make a classlist first? (y/n):")
    if inp.lower() in ["y", "n"]:
        done = True
        #rest of your code

What I have done here is I have put the input checking code within a while loop, which repeats while the done variable is False. If the user enters valid input, then done becomes True and the repetition stops. If the user enters invalid input, then they are prompted again.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53