Making a multiple-choice question is a common task when developing software applications. Python is a popular programming language for creating software applications. In this tutorial, we will learn how to make a multiple-choice question in Python.
Steps to Make a Multiple-Choice Question in Python
1. Firstly, we need to create a list of questions and store each of them in a separate variable.
1 |
ques_1 = "What is the capital of India?\n(a) Mumbai\n(b) Delhi\n(c) Bangalore\n(d) Chennai\nAnswer: " |
2. Next, we need to create a dictionary of answers for each question.
1 |
answers = {"ques_1":"b", "ques_2":"a", "ques_3":"c"} |
3. Now, we need to create a function to display the question and options to the user. We can use the input function to get the user’s answer.
1 2 3 4 |
def display_question(question): print(question) user_answer = input() return user_answer |
4. We also need to create a function to check whether the user’s answer matches the correct answer or not.
1 2 3 4 5 |
def check_answer(question, user_answer): if user_answer == answers[question]: print("Correct answer!") else: print("Incorrect answer!") |
5. Finally, we need to call the display_question function for each question and pass the question variable as an argument. We also need to pass the user’s answer to the check_answer function to check whether the answer is correct or not.
1 2 |
ans_1 = display_question(ques_1) check_answer("ques_1", ans_1) |
Conclusion
In this tutorial, we have learned how to make a multiple-choice question in Python. We used variables, dictionaries, and functions to create the question and check the user’s answer. This method can be used to create multiple-choice questions for various applications.
Here is the full code used in this tutorial:
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 |
# Creating variables for each question ques_1 = "What is the capital of India?\n(a) Mumbai\n(b) Delhi\n(c) Bangalore\n(d) Chennai\nAnswer: " ques_2 = "What is the largest country in the world by area?\n(a) Russia\n(b) China\n(c) USA\n(d) Canada\nAnswer: " ques_3 = "What is the currency of Japan?\n(a) Yen\n(b) Won\n(c) Dollar\n(d) Euro\nAnswer: " # Creating a dictionary of answers for each question answers = {"ques_1":"b", "ques_2":"a", "ques_3":"c"} # Creating a function to display the question and get user's answer def display_question(question): print(question) user_answer = input() return user_answer # Creating a function to check user's answer against correct answer def check_answer(question, user_answer): if user_answer == answers[question]: print("Correct answer!") else: print("Incorrect answer!") # Displaying each question and getting user's answer ans_1 = display_question(ques_1) check_answer("ques_1", ans_1) ans_2 = display_question(ques_2) check_answer("ques_2", ans_2) ans_3 = display_question(ques_3) check_answer("ques_3", ans_3) |