Yes or No question in Python

To create yes or no questions in Python, we need to have a way of asking a question and taking input from the user. This can be achieved using the input(<prompt>) function in Python 3 and raw_input(<prompt>) in Python 2.

In this case, the question is asked on the <prompt>, and the answer from the user is accepted. Once the response is typed, the prompt is exited by pressing the ENTER key. This article will show a step-by-step approach to creating yes/no questions in Python.

Note: The last step has the final answer.

Step 0: Accepting user input

Output:

Have you ever pulled a successful prank? (yes or no): yes
You answered yes

The code above successfully issues a prompt and prints the input, but something is wrong. The user can give any response (not just “yes” or “no”). Let’s address that in the next step.

Step 1: Accept an Answer and Check if it is “yes” or “no”

Output (Take 1)

Have you ever pulled a successful prank? (yes or no): null
Your answer can only be yes or no. You answered null

The prompt accepts any answer now, but we have used conditional statements to check that the answer can only be “yes” or “no.” But there is yet another problem. The code is too restrictive when it comes to the responses; for example, the answer “Yes”, “YES”, “yes”, and “y” may mean the same thing, but our code only accepts “yes” as a valid answer. Let’s fix that.

Step 2: Accepting varieties of the same answer

Output (Take 1):

Have you ever pulled a successful prank? (yes or no): YEs
You answered yes

In the above case, the code now accepts an answer, turns it into lowercase, and compares it against three possible responses in a category (you can give more). So far, the user has one chance to answer the question. Let’s modify our code to accept some retries.

Step 3: The Final Answer

Output (truncated):

Have you ever pulled a successful prank? (yes or no): yu
Your answer can only be yes/y/1 or no/n/0. You answered yu
…
Your answer can only be yes/y/1 or no/n/0. You answered jkl
Number of retries exceeded. Exiting and return -1.