Here's a simple command-line voting system for an election implemented in Python. This system includes voter registration, candidate management, vote casting, and result calculation.
python
class VotingSystem:
def __init__(self):
self.voters = {}
self.candidates = {}
self.votes = {}
def register_voter(self, voter_id):
if voter_id in self.voters:
print("Error: Voter ID already registered.")
return False
self.voters[voter_id] = False # False means hasn't voted yet
print(f"Voter {voter_id} registered successfully.")
return True
def add_candidate(self, candidate_id, name):
if candidate_id in self.candidates:
print("Error: Candidate ID already exists.")
return False
self.candidates[candidate_id] = name
self.votes[candidate_id] = 0
print(f"Candidate {name} ({candidate_id}) added successfully.")
return True
def cast_vote(self, voter_id, candidate_id):
# Check if voter exists
if voter_id not in self.voters:
print("Error: Voter not registered.")
return False
# Check if voter already voted
if self.voters[voter_id]:
print("Error: Voter has already cast a vote.")
return False
# Check if candidate exists
if candidate_id not in self.candidates:
print("Error: Invalid candidate ID.")
return False
# Record vote
self.voters[voter_id] = True
self.votes[candidate_id] += 1
print(f"Vote cast successfully for {self.candidates[candidate_id]}.")
return True
def display_results(self):
print("\nELECTION RESULTS")
print("-----------------")
total_votes = sum(self.votes.values())
if total_votes == 0:
print("No votes cast yet.")
return
# Sort candidates by votes (descending)
sorted_candidates = sorted(
self.votes.items(),
key=lambda x: x[1],
reverse=True
)
# Display results
for candidate_id, vote_count in sorted_candidates:
percentage = (vote_count / total_votes) * 100 if total_votes > 0 else 0
print(f"{self.candidates[candidate_id]}: {vote_count} votes ({percentage:.1f}%)")
# Check for winner
winner = sorted_candidates[0]
print(f"\nWINNER: {self.candidates[winner[0]]} with {winner[1]} votes!")
def display_voters(self):
print("\nREGISTERED VOTERS:")
for voter, voted in self.voters.items():
status = "Voted" if voted else "Not Voted"
print(f"{voter} - {status}")
def display_candidates(self):
print("\nCANDIDATES:")
for cid, name in self.candidates.items():
print(f"{cid}: {name}")
# Main program
def main():
system = VotingSystem()
# Create sample data
system.add_candidate("C1", "Alice Anderson")
system.add_candidate("C2", "Bob Brown")
system.register_voter("V001")
system.register_voter("V002")
system.register_voter("V003")
while True:
print("\nVOTING SYSTEM MENU")
print("1. Register Voter")
print("2. Add Candidate")
print("3. Cast Vote")
print("4. Display Results")
print("5. Show Registered Voters")
print("6. Show Candidates")
print("7. Exit")
choice = input("Enter your choice: ")
if choice == "1":
voter_id = input("Enter voter ID: ")
system.register_voter(voter_id)
elif choice == "2":
candidate_id = input("Enter candidate ID: ")
name = input("Enter candidate name: ")
system.add_candidate(candidate_id, name)
elif choice == "3":
system.display_candidates()
voter_id = input("Enter your voter ID: ")
candidate_id = input("Enter candidate ID: ")
system.cast_vote(voter_id, candidate_id)
elif choice == "4":
system.display_results()
elif choice == "5":
system.display_voters()
elif choice == "6":
system.display_candidates()
elif choice == "7":
print("Exiting voting system...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Features:
Voter Registration:
Unique voter IDs prevent duplicate registrations
Tracks whether a voter has cast their ballot
Candidate Management:
Add candidates with unique IDs
Stores candidate names and vote counts
Voting Process:
Prevents unregistered voters from voting
Ensures one vote per voter
Validates candidate selection
Results Display:
Shows vote counts and percentages
Sorts candidates by vote count
Declares a winner
Data Views:
View registered voters and their voting status
See all available candidates
How to Use:
Start by registering voters and adding candidates
Use the "Cast Vote" option to record votes
View results anytime using "Display Results"
Check voter status and candidate lists as needed
Security Notes:
This is a simplified system for demonstration purposes
Real-world systems would require:
Voter authentication
Encrypted data storage
Audit trails
Secret ballots
Prevention of tampering
Enhancements Considered:
Add candidate parties/affiliations
Implement different voting methods (ranked choice, etc.)
Add admin authentication
Persist data using file storage/database
Add election time limits
This system demonstrates core voting principles while maintaining simplicity. Run the program and follow the menu prompts to interact with the system.