How to Ask a Yes-or-No Question in Python

If you’re developing a Python script where you would need the user’s response for processing (like a yes or no answer), Python makes it easy to manage this with the input() function. This tutorial will guide you on how to ask for and handle such yes-or-no questions in Python.

Step 1 – Basic Input Function

First, let’s understand the input() function. This Python function prompts the user for a line of input from the user, exactly like a prompt on the command line.

Step 2 – Formatting the User Response

In most cases, we want to standardize the response. For that, we should strip white spaces and convert the response to lowercase, so that ‘yes’, ‘Yes’, ‘YES’ etc. all become ‘yes’. This way, you can easily manage the user responses.

Step 3 – Checking the User Response

Now that we have the user response formatted, we can check it using an if-else statement. If the response is ‘yes’, then one course of action can be followed; otherwise (assuming it will be ‘no’), the script will execute another set of code.

However, remember that this code doesn’t validate the user’s input and will consider any response other than ‘yes’ as a ‘no’.

Step 4 – Validating the User Response

If you wish to strictly accept only ‘yes’ or ‘no’ as valid responses, you can build a validation loop using the while statement. If the response is neither ‘yes’ nor ‘no’, it keeps asking again.

Full Example Code

Want to continue? (Yes/No) yes
Continuing...

Conclusion

In Python, the input() function allows us to prompt the user for input. To handle yes-or-no questions, we strip white spaces and convert the input to lower case. With a while loop, we can validate the user’s response to strictly be ‘yes’ or ‘no’. This covers all the key steps to effectively handle yes-or-no questions in Python!