|
| 1 | +class VotingSystem: |
| 2 | +def __init__(self): |
| 3 | +self.candidates = {} |
| 4 | +self.votes = {} |
| 5 | +self.voters = set() |
| 6 | +def register_candidate(self, candidate_id, candidate_name): |
| 7 | +if candidate_id in self.candidates: |
| 8 | +print("Candidate already registered!") |
| 9 | +else: |
| 10 | +self.candidates[candidate_id] = candidate_name |
| 11 | +self.votes[candidate_id] = 0 |
| 12 | +print(f"Candidate '{candidate_name}' registered successfully.") |
| 13 | +def cast_vote(self, voter_id, candidate_id): |
| 14 | +if voter_id in self.voters: |
| 15 | +print("You have already voted.") |
| 16 | +return |
| 17 | +if candidate_id not in self.candidates: |
| 18 | +print("Invalid candidate ID.") |
| 19 | +return |
| 20 | +self.voters.add(voter_id) |
| 21 | +self.votes[candidate_id] += 1 |
| 22 | +print(f"Vote casted for {self.candidates[candidate_id]} by voter {voter_id}.") |
| 23 | +def display_results(self): |
| 24 | +print("\n--- Voting Results ---") |
| 25 | +for candidate_id, vote_count in self.votes.items(): |
| 26 | +print(f"{self.candidates[candidate_id]}: {vote_count} votes") |
| 27 | +def is_valid_candidate(self, candidate_name): |
| 28 | +return len(candidate_name.strip()) > 0 |
| 29 | +def main(): |
| 30 | +system = VotingSystem() |
| 31 | +while True: |
| 32 | +print("\n--- Voting System ---") |
| 33 | +print("1. Register Candidate") |
| 34 | +print("2. Cast Vote") |
| 35 | +print("3. Display Results") |
| 36 | +print("4. Exit") |
| 37 | +choice = input("Enter your choice: ") |
| 38 | +if choice == '1': |
| 39 | +candidate_id = input("Enter candidate ID: ") |
| 40 | +candidate_name = input("Enter candidate name: ") |
| 41 | +if system.is_valid_candidate(candidate_name): |
| 42 | +system.register_candidate(candidate_id, candidate_name) |
| 43 | +else: |
| 44 | +print("Invalid candidate name. Name must not be empty.") |
| 45 | +elif choice == '2’: |
| 46 | +voter_id = input("Enter your voter ID: ") |
| 47 | +print("Available candidates:") |
| 48 | +for candidate_id, candidate_name in |
| 49 | +system.candidates.items(): |
| 50 | +print(f"{candidate_id}:{candidate_name}") candidate_id = input("Enter candidate ID to vote for: ") |
| 51 | +system.cast_vote(voter_id, candidate_id) |
| 52 | +elif choice == '3’: |
| 53 | +system.display_results() |
| 54 | +elif choice == '4’: |
| 55 | +print("Exiting voting system.") |
| 56 | +break |
| 57 | +else: |
| 58 | +print("Invalid choice. Please try again.") |
| 59 | +if __name__ == "__main__": |
| 60 | +main() |
0 commit comments