0

I need help with my if/else statement for a Marvel character questionnaire.

I want to make sure the user can't enter any letters besides A,B,C or D.

if str(input())) not ('A','B','C','D')
else ("ask them again");

How do I add while to make the code ask for input again if no valid answer was given?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
James Bond
  • 1
  • 1
  • 4
  • [**The official python tutorial**](https://docs.python.org/3/tutorial/) – Remi Guan Dec 12 '15 at 07:32
  • 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) – hc_dev Jan 28 '23 at 17:48

2 Answers2

2
answer = ""
possibleAnswers = {"A","B","C","D"}

while answer not in possibleAnswers:
    answer = input(f"Type a letter, one of {','.join(possibleAnswers)}:")
hc_dev
  • 8,389
  • 1
  • 26
  • 38
AJ X.
  • 2,729
  • 1
  • 23
  • 33
  • Thanks alot I appreciate the help. – James Bond Dec 12 '15 at 03:40
  • A set of valid options is good-practice to compare input (unique, fast, readable). A set variable can also be used to show the user valid options when prompting for input. – hc_dev Jan 28 '23 at 17:50
1

One simple option is check each letter:

choice='f'
while choice!='A' and choice!='B' and choice!='C' and choice!='D':
  choice=input('Enter letter')

if you want to check regardless of case use .upper() right after the input(..)

depperm
  • 10,606
  • 4
  • 43
  • 67