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