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.:
- answer = input("Enter yes or no: ")
- if answer == "yes":
- # Do this.
- elif answer == "no":
- # Do that.
- else:
- print("Please enter yes or no.")
You can go further and loop the question to allow for repeated incorrect input:
- answer = None
- while answer not in ("yes", "no"):
- answer = input("Enter yes or no: ")
- if answer == "yes":
- # Do this.
- elif answer == "no":
- # Do that.
- else:
- 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.