Asking questions in Pyhton entails asking a question and accepting an answer from the user.
This is achieved using the input(<prompt>) function in Python 3 or raw_input(<prompt>) in Python 2. The question is passed to the function as <prompt>, and the user’s input is accepted. Once the answer has been typed, the user can exit the prompt by pressing the ENTER key.
In this article, we will learn how to create different types of questions in Python using the input() function.
Asking Open-Ended Questions
Open-ended questions are free-form questions that allow users to give any answer based on their knowledge. We can create an open question in Python with a snippet like the one shown below.
1 2 |
answer = input("What is your name? ") print(f"Your answer is {answer}") |
Output:
What is your name? Tomasz Your answer is Tomasz
You can also use a for-loop to ask several open-ended questions.
questions = [ "What is your name? ", "What is your registration number? ", "When were you born? ", ] for question in questions: answer = input(question) print(answer)
Output:
What is your name? Tomasz Tomasz What is your registration number? 1595 1595 When were you born? 1995 1995
Asking Closed-Ended Questions
These questions can only be answered by picking the answer from a list of given options.
We will work on two types of closed questions – dichotomous and multiple choice. The former are questions with two answer options, but the latter may have more.
Asking dichotomous questions
In this case, we need to ask a question, accept the answer and check if the answer matches the two choices given. Here is how to ask a Yes or No question in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def AskQuestion(question): """ Arg: question Ask a question, and check if the answer is yes or no. If not, return None else, return the answer. """ # strip() removes trailing whitespace from the answer. answer = input(question).strip() if answer == "yes": print("You answered yes.") elif answer == "no": print("You answered no.") else: print(f"You can only answer yes or no. Your answer is {answer}.") return None return answer question = "Do you like traveling? (yes/no) " AskQuestion(question) |
Output (Take 1):
Do you like traveling? (yes/no) yes You answered yes.
Output (Take 2):
Do you like traveling? (yes/no) success You can only answer yes or no. Your answer is success.
The AskQuestion() function now accepts only “yes” or “no” as the valid answers – the feature for the closed-ended questions to have two options.
But there’s a problem. The code is too restrictive when it comes to answers. It only accepts the answers “yes” and “no” but not the varieties that may mean the same answer. For example, “yes”, “Yes”, “YES”, “y” or “1” can be used to mean the same thing, and “no”, “NO”, “n” or “0” to mean the contrary. Let’s add this to our function above and also allow the user to retry on invalid answers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
def AskQuestion1(question, n_retries=3): # initialize the number of tries. trial = 0 while True: # Issue the prompt answer = input(f"{question} (yes or no): ") # Remove trailing white spaces from the answer and turn it to lowercase. # That means "YES", "Yes", and "YEs" will all be converted to "yes". answer = answer.strip().lower() # Check the answer - providing varieties of the same answer. if answer in ["yes", "y", "1"]: print("You answered yes.") # or do something return "yes" elif answer in ["no", "n", "0"]: print("You answered no.") # or do something else return "no" else: # Valid answer not given, print a message and retry. print(f"Your answer can only be yes/y/1 or no/n/0. You answered {answer}.") if trial == n_retries: # If the number of trials=n_tries, print a statement and break the while loop. print("Number of retries exceeded.") break # Increase the number of trials by 1 trial = trial + 1 # If no valid answer is given after n_retries exist with -1 return value return -1 AskQuestion1("Do you like ice cream?") |
Output:
Do you like ice cream? (yes or no): 7 Your answer can only be yes/y/1 or no/n/0. You answered 7. Do you like ice cream? (yes or no): y You answered yes.
Asking Multi-Choice Questions
Like we did in dichotomous questions, we can use if-else statements to check our answers. In this case, we issue as many if-conditions as the number of possible choices. Let’s start with a simple example.
1 2 3 4 5 6 7 8 9 10 11 |
answer = input( "What is your favorite programming language? (Python, JavaScript, R) " ).lower() if answer == "python": print(f"You chose Python") elif answer == "javascript": print(f"You chose JavaScript") elif answer == "r": print(f"You chose R") else: print("The answer provided is not among the choices given.") |
Output:
What is your favorite programming language? (Python, JavaScript, R) Python You chose Python
The code above works for a simple question, but it may not be efficient if we have several choices. That form of asking a question may also not work for multiple-choice questions with right or wrong answers. For example, asking the question 2*3=? with the options being (8, 6, 5). In this case, we need to check not only the answer to come from the options but also the correctness of the answer given. Let’s modify the code above to do that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import string def AskMultiplChoice(question, choices, correct=None): # Convert each value in the choices tuple/list into string. # This allows the user to pass non-string values. choices = tuple(map(str, choices)) print("Question: ", question) # Get the number of choices using len() n_choices = len(choices) # Get the uppercase ASCII alphabets matching the number of choices. # For example, if the choices are ("9", "0", "1"), letters become ["A", "B", "C"] # and if the choice is ("Chicago", "Toronto", "Nairobi", "Berlin", "Paris") letters # become ["A", "B", "C", "D", "E"] letters = list(string.ascii_uppercase[:n_choices]) # this line converts zip(["A", "B"], ("9", "0")) becomes [("A" : "9"), ("B" : "0")] choicesab = [f"{i[0]} : {i[1]}" for i in zip(letters, choices)] # * unpacks the values on the variable and sep="\n" ensures each choice is printed in new line print("Choices: ", *choicesab, sep="\n") # Ask the question and show the possible letters determined on the letters variable above answer = input(f"Type your answer here {letters}: ") # Create an assertion to confirm that the user is picking the choice available only. # For example, if the choices we have is A, B, and C, typing E will yield AssersionError. assert ( answer in letters ), f"Answer can only be any of the following letters: {letters}" # if correct is None, there's no right or wrong answer. # For example, when asking, "What is your favorite programming language?" if correct is None: # If there's no right or wrong answer, we return the picked choice # index(answer) returns the index of the answer. For example, # for the question 2*3 with options (8, 6, 5), list(letters).index(answer)=1 print(f"You chose: {choices[list(letters).index(answer)]}") return choices[list(letters).index(answer)] else: # Check the index of the correct answer index_of_correct = list(choices).index(correct) # Reference the correct letter from the correct answer correct_letter = letters[index_of_correct] if answer == correct_letter: print(f"Correct! You chose {answer}") else: print( f"You chose: {answer}. The correct answer is {correct_letter}:{correct}" ) return answer # Question with one correct answer and four choices in total question = "4*8+6=?" choices = (56, 52, 80, 38) correct = str(4 * 8 + 6) AskMultiplChoice(question, choices, correct) # 4 choices with one correct answer question = "Brazil is located in?" choices = ("North America", "South America", "Asia") correct = "South America" AskMultiplChoice(question, choices, correct) # A question that does not have a right or wrong answer. question = "What is your programming language?" choices = ("Python", "JavaScript", "Rust", "R", "Java") AskMultiplChoice(question, choices) |
Output:
Question: 4*8+6=? Choices: A : 56 B : 52 C : 80 D : 38 Type your answer here ['A', 'B', 'C', 'D']: D Correct! You chose D Question: Brazil is located in? Choices: A : North America B : South America C : Asia Type your answer here ['A', 'B', 'C']: A You chose: A. The correct answer is B:South America Question: What is your programming language? Choices: A : Python B : JavaScript C : Rust D : R E : Java Type your answer here ['A', 'B', 'C', 'D', 'E']: A You chose: Python
Conclusion
This article discussed how to ask questions in Python – open and closed questions. We covered different examples to show how to ask questions in the correct way using the input() function. After going through the post, you should be able to easily tweak the code to fit your used case.