Search code examples
pythonloopswhile-loopuser-input

How to run python loop until correct input string is entered


I have to write a code that will execute the below while loop only if the user enters the term "Cyril".

I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.

number_list = []
attempts = 0
name = False
number = 0

name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
    name = True
else:
    print("\nThat is incorrect, please restart the program and try again.\n")  

if name:
    number = int(input("Correct! Please enter any number between -1 and 10: "))
    while number > -1:
        number_list.append(number)
        number = int(input("\nThank you. Please enter another number between -1 and 10: "))
    if number > 10:
        print("\nYou have entered a number outside of the range, please try again.\n")
        number = int(input("Please enter a number between -1 and 10: "))
    elif number < -1:
        print("\nYou have entered a number outside of the range, please try again. \n")
        number = int(input("Please enter a number between -1 and 10: "))
    elif number == -1:
        average_number = sum(number_list) / len(number_list)
        print("\nThe average number you have entered is:", round(average_number, 0))

Solution

  • Change beginning of code to:

    while True:
        name_question = input("You are the President of RSA, what is your name?: ")
        if name_question == "Cyril":
            name = True
            break
        else:
            print("\nThat is incorrect, please try again.\n")