Casa > 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.

De Battat Balson

Intel core i5-1035G1 vs i5-10210U qual deles é melhor em geral? :: Quais os telefones de bandeira que veremos ter as maiores quedas de preços na venda deste ano (2020) Big Billion Days na Amazon?