0

I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.

CODE:

while True:
    try:
        choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
        assert choice == 1
        if choice == (1):
            userInp = input("TYPE: ")

            words = userInp.split()

            start_count = 0
            for word in words:
                word = word.lower()
                if word.startswith("u"):
                    start_count += 1

            print(f"You wrote {len(words)} words.")
            print(f"You wrote {start_count} words that start with u.")
            again = str(input("Again? (Y or N) "))
            again = again.upper()
            if again == "Y":
                continue
            elif again == "N":
                break
    except AssertionError:
        print("Please type a given option.")
    except ValueError:
        print("Please type a given option.")

EDIT: So I have made some progress but I have one last problem

CODE:

 while True:
    try:
        choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
        assert choice == 1
        if choice == (1):
            userInp = input("TYPE: ")

            words = userInp.split()

            start_count = 0
            for word in words:
                word = word.lower()
                if word.startswith("u"):
                    start_count += 1

            print(f"You wrote {len(words)} words.")
            print(f"You wrote {start_count} words that start with u.")
            while True:
                again = input("again? (Y or N)")
                if again not in "yYnN":
                    continue
                break
        if again == "Y":
            continue
        elif again == "N":
            break
    except AssertionError:
        print("Please type a given option.")
    except ValueError:
        print("Please type a given option.")

The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?

rabin
  • 11
  • 3
  • Does this answer your question? [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) – JonSG Feb 12 '22 at 15:35

1 Answers1

0

You could create another loop (inside this main loop) where you are asking for input, and have a try block there, so that it loops just the section where the user is giving input until they give correct input.

Vizzyy
  • 522
  • 3
  • 11
  • but if i were to break it would only stop looping the again section it would just reoutput the top line – rabin Feb 12 '22 at 15:35