In this tutorial, you’ll discover a simple way to create an interactive poll using Python. The process utilizes Python’s built-in libraries to input data from the user and present it in a clear and organized manner. With this knowledge, you’ll be ready to collect and respond to user input in your own Python projects!
Step 1: Import Python Libraries
For this example, we only need one library: collections. This built-in Python library will help us tally the votes of our poll. Add the following line at the top of your Python file:
1 |
import collections |
Step 2: Create the Poll
Now, we need to define the poll. Here is a simple poll question with two possible responses: ‘Yes’ and ‘No’.
1 2 3 |
poll = [] poll_question = "Do you like Python? " poll_answers = ['Yes', 'No'] |
Step 3: Gather User Responses
Next, we need to collect responses from users. We can use Python’s built-in function input() for this task. The loop will continue until a user inputs an ‘end’ response.
1 2 3 4 5 6 7 8 |
while True: response = input(poll_question) if response == 'end': break if response in poll_answers: poll.append(response) else: print("Invalid response. Please answer 'Yes' or 'No'.") |
Step 4: Count the Votes
Lastly, we will use collections.Counter(), which counts the frequency of each item in our list:
1 2 |
results = collections.Counter(poll) print("Poll Results: ", results) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import collections poll = [] poll_question = "Do you like Python? " poll_answers = ['Yes', 'No'] while True: response = input(poll_question) if response == 'end': break if response in poll_answers: poll.append(response) else: print("Invalid response. Please answer 'Yes' or 'No'.") results = collections.Counter(poll) print("Poll Results: ", results) |
Conclusion
Creating a poll in Python is simple and straightforward. With the use of Python’s built-in libraries and functions, we’ve made an interactive poll that collects and records user input and then presents a tally of the results.
Once you’ve grasped these basic concepts, you can easily modify this to suit your needs, adding more poll options, or even creating multiple polls. Happy coding!