QNA > I > I’m New To Python, How Can I Write A Yes/No Question?

I’m new to Python, how can I write a yes/no question?

In its simplest form you just ask the question, get the answer and process the answer, i.e.:

  1. answer = input("Enter yes or no: ") 
  2. if answer == "yes": 
  3. # Do this. 
  4. elif answer == "no": 
  5. # Do that. 
  6. else: 
  7. print("Please enter yes or no.") 

You can go further and loop the question to allow for repeated incorrect input:

  1. answer = None 
  2. while answer not in ("yes", "no"): 
  3. answer = input("Enter yes or no: ") 
  4. if answer == "yes": 
  5. # Do this. 
  6. elif answer == "no": 
  7. # Do that. 
  8. else: 
  9. print("Please enter yes or no.") 

Additions to the either version can allow for conversion between lower and upper case in order to validate the input.

Thanks to Chase Hanson for suggesting a now-implemented modification to my original answer. And to Heath Lee Fournier for pointing out a typo.

This code has now been tested in Python 3.6.1.

Di Adabelle

Dovresti prendere un telefono Android di punta di 2 o 3 anni fa? :: Quale telefono è meglio, Huawei Mate 10 Lite o Huawei P20 Lite?
Link utili