To ask a question with Python, you can use the input() function. input() will prompt the user with the text and will return whatever text was input by the user.
question = input("Do you want some ice cream?")
When creating programs in Python, the ability to be able to ask questions and get a response from the user can be very useful.
To ask a question with Python, you can use the input() function.
input() prints text to the terminal and waits for a response. The user then can type and can submit an answer by pressing ‘Enter’.
Below is an example of how to ask a question and store the response in a variable in Python.
question = input("Do you want some ice cream?")
How to Ask a Yes or No Question in Python with input()
If you want to ask a yes or no question with input() in Python, then you need to make sure that you perform validation on your inputs to know if the user is passing the response you want.
For example, below is a yes or no question you can ask with Python.
question = input("Do you want some ice cream? Enter yes or no:)
Here, you need to make sure that you perform various checks which will make sure you are interpreting the response accurately.
In the question above, we are expecting “yes” or “no”. In this case, you can do the following to make sure the user only inputs these responses.
Below is an example showing you how to make sure that you get a “yes” or “no”, and you ensure that the user answers your question with the response you want.
valid_response = False
while valid_response == False:
question = input("Do you want some ice cream? Enter yes or no:")
if question == "yes":
valid_response = True
#Do something with yes
elif question == "no":
valid_response = True
#Do something with no
Depending on how you want to handle this situation, you can do different things with loops or if-elif-else statements.
Hopefully this article has been useful for you to learn how to ask questions with input() in Python.