Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
440: Building a Simple Poll/Voting Script
Imagine you're organizing a small get-together and you want to decide on a movie. Instead of a chaotic group chat, you set up three jars on a table—one labeled "Sci-Fi," one "Horror," and one "Comedy." You give every guest a single marble. They walk up, drop their marble into their preferred jar, and move on. At the end of the night, you just count the marbles in each jar to find the winner. Simple, right?
When we build a voting script in Python, we're doing the exact same thing, just with data structures instead of glass jars. Here is how that mapping works:
- The Jars: These are the keys in a Python dictionary. Each key represents a candidate or an option.
- The Marbles: These are the values associated with those keys. Every time someone votes, we just increment that number by one.
- The Voting Process: This is a loop that keeps asking for input until a specific "exit" command is given.
- The Final Count: This is where we iterate through our dictionary and print out the totals.
Setting Up the Digital Ballot Box
We don't want to manually add keys every time someone votes; that's a recipe for bugs. Instead, I prefer to define the options upfront. This ensures that if someone tries to vote for "Pineapple Pizza" in a "Pepperoni vs. Cheese" poll, the program doesn't just crash or create a new category on the fly.
# Our predefined 'jars'
votes = {
"Sci-Fi": 0,
"Horror": 0,
"Comedy": 0
}
Handling the Human Element
Here is where things usually go sideways. Users are unpredictable. One person will type "Sci-Fi", another will type "sci-fi", and a third might just type "scifi". If you're not careful, Python will treat those as three different options. I always recommend normalizing the input—forcing everything to a specific case—so the computer sees them as the same thing.
while True:
user_choice = input("Enter your vote (Sci-Fi, Horror, Comedy) or 'quit' to stop: ").strip().title()
if user_choice == "Quit":
break
if user_choice in votes:
votes[user_choice] += 1
print(f"Vote cast for {user_choice}!")
else:
print("That's not a valid option. Try again.")
Notice I used .strip().title(). This cleans up any accidental leading spaces and ensures the first letter is capitalized, matching our dictionary keys exactly. It's a small detail, but it's the difference between a professional tool and a fragile script.
Calculating the Winner
Once the loop breaks, we have a dictionary full of totals. We could just print the dictionary, but that's ugly. I like to loop through the items to present the data cleanly. If you want to get fancy, you can track the maximum value to announce the actual winner.
print("\n--- Final Results ---")
for option, count in votes.items():
print(f"{option}: {count} votes")
# Finding the winner
winner = max(votes, key=votes.get)
print(f"\nThe winner is {winner}!")
The max(votes, key=votes.get) trick is a bit of Python magic. It tells Python: "Look at the votes dictionary, but instead of finding the max key (which would just be alphabetical), find the key that has the maximum value."
📋 Practical Task
Build the "Office Coffee Machine Preference Poll"
Your task is to create a script that helps an office manager decide which coffee brand to buy.
- Create a dictionary with three specific brands: "Arabica", "Robusta", and "Decaf", all starting at 0 votes.
- Implement a
whileloop that accepts user input. - Ensure the script handles case-insensitivity (so "arabica" and "ARABICA" both count).
- Allow the user to type "done" to stop the voting process.
- After the loop ends, print the total votes for each brand and announce which brand won.
- Bonus Challenge: Add a check to ensure that if there is a tie for the winner, the script mentions that it's a tie rather than just picking one name.
There are no comments for now.