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.
Artigos semelhantes
- Where can I find somebody to write a Python program for a FLAMES game?
- Can you write mobile apps in Python/Django?
- If I buy a new MacBook Air 2020 (i5-512gb), how long (years) can I use it or should I wait for the new MacBook Pro 2020?
- QA Interview question: How do I test a music player app on a phone?