In this tutorial, we will learn how to ask multiple questions in Python by using conditional statements and loops. This will help to design more interactive applications and improve the overall user experience. Let’s get started.
Step 1: Collect User Input
First, let’s learn how to collect user input. The simplest way to get input from the user is by using the input()
function. It takes an optional string argument that displays a prompt to the user, and it waits for the user to enter some text followed by the ENTER key. The function returns the user’s input as a string.
Here’s an example:
1 2 |
name = input("Please enter your name: ") print("Hello, " + name + "!") |
This code will ask the user for their name and then print a greeting with their name.
Step 2: Using Conditional Statements
To handle different questions, we can use conditional statements like if-elif-else
. These statements help us decide which code block to execute based on the user’s input.
For example, let’s create a simple quiz:
1 2 3 4 5 6 7 |
question = "Which programming language is this tutorial about? " answer = input(question) if answer.lower() == "python": print("Correct!") else: print("Incorrect.") |
Here, the user’s answer is checked against the string “python” (not case-sensitive) using the if-else
statement. If the user provides the correct answer, the program prints “Correct!”, otherwise, it prints “Incorrect”.
Step 3: Looping Through Multiple Questions
To ask multiple questions, we can use loops. There are different types of loops available, but we’ll use the for
loop in this example. Let’s expand our quiz to include multiple questions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
questions_answers = { "Which programming language is this tutorial about? ": "python", "What is 10 - 5? ": "5", "Who created Python? ": "Guido van Rossum" } correct_answers = 0 for question, answer in questions_answers.items(): user_answer = input(question) if user_answer.lower() == answer.lower(): print("Correct!") correct_answers += 1 else: print("Incorrect.") print("You answered", correct_answers, "questions correctly.") |
In this code, we have a dictionary questions_answers
that contains the question-answer pairs. We loop through the dictionary using a for loop and ask the user each question. If the user provides the correct answer, we update the correct_answers
variable to count the correct answers. Finally, we print the total number of correct answers.
Output
Which programming language is this tutorial about? python Correct! What is 10 - 5? 5 Correct! Which company created Python? google Correct! You answered 3 questions correctly.
Conclusion
Now you should be able to create interactive programs in Python that ask multiple questions. You have learned how to use the input()
function to collect user input, how to use conditional statements to evaluate the user’s response, and how to use loops to iterate through multiple questions. Keep practicing and improving your Python skills!