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.
1 |
response = input("Want to continue? (Yes/No) ") |
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.
1 |
response = input("Want to continue? (Yes/No) ").strip().lower() |
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.
1 2 3 4 |
if response == 'yes': print("Continuing...") else: print("Stopped!") |
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.
1 2 3 |
valid_responses = ['yes', 'no'] while response not in valid_responses: response = input("Invalid response. Please reply with 'yes' or 'no': ").strip().lower() |
Full Example Code
1 2 3 4 5 6 7 8 9 10 |
response = input("Want to continue? (Yes/No) ").strip().lower() valid_responses = ['yes', 'no'] while response not in valid_responses: response = input("Invalid response. Please reply with 'yes' or 'no': ").strip().lower() if response == 'yes': print("Continuing...") else: print("Stopped!") |
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!