0% found this document useful (0 votes)
9 views

File

Uploaded by

Aniket Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

File

Uploaded by

Aniket Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

VotingMachine Class Definition

class VotingMachine:

Defines the VotingMachine class, which encapsulates the voting logic and data.

Constructor Method

def __init__(self, candidates_file): self.candidates =


self.load_candidates(candidates_file) self.voters = set() self.vote_count =
{number: 0 for number in self.candidates} # Initialize vote counts

Initializes a new VotingMachine instance with:

candidates: loaded from the specified file.

voters: a set to track voters and prevent double voting.

vote_count: a dictionary to track the number of votes each candidate receives,


initialized to zero.

Load Candidates Method

def load_candidates(self, candidates_file): """Load candidates from a file and


return a dictionary."""

Defines a method to read candidates from a specified file and return them as a
dictionary.

candidates = {}

Initializes an empty dictionary to store candidates.

try: with open(candidates_file, 'r') as file:


Opens the candidates file in read mode, ensuring proper closure after reading.

for line in file: line = line.strip()

Iterates over each line in the file, stripping whitespace.

if line: number, name = line.split(',', 1) candidates[number] = name.strip()

Splits non-empty lines into candidate number and name, adding them to the
candidates dictionary.

if not candidates: raise ValueError("No candidates found.")

Raises an exception if no candidates are found.

return candidates

Returns the populated candidates dictionary.

except FileNotFoundError: raise FileNotFoundError("Candidates file not found.")


except Exception as e: raise Exception(f"An error occurred while loading
candidates: {e}")

Catches and raises specific exceptions related to file handling or other errors.

Vote Method

def vote(self, voter_id, candidate_number): """Cast a vote for a candidate."""

Defines a method for casting a vote, taking voter_id and candidate_number as


parameters.
if voter_id in self.voters: raise Exception("This voter has already voted.")

Checks if the voter has already voted, raising an exception if they have.

if candidate_number not in self.candidates: raise ValueError("Candidate number not


found.")

Checks if the candidate number is valid, raising an exception if it is not.

self.voters.add(voter_id) self.vote_count[candidate_number] += 1 # Increment the


vote count

Adds the voter's ID to the voters set and increments the count for the selected
candidate.

print(f"Vote cast for {self.candidates[candidate_number]} (Candidate


#{candidate_number}) by voter {voter_id}.")

Prints a confirmation message for the vote cast.

Display Candidates Method

def display_candidates(self): """Display the list of candidates with their assigned


numbers."""

Defines a method to display the candidates.

print("Candidates:") for number, name in self.candidates.items(): print(f"{number}:


{name}")

Iterates through the candidates dictionary and prints each candidate's number and
name.

Display Results Method


def display_results(self): """Display the final vote count for each candidate."""

Defines a new method to show the final vote counts.

print("\nFinal Vote Count:") for number, count in self.vote_count.items():


print(f"{self.candidates[number]} (Candidate #{number}): {count} votes")

Prints the total votes each candidate received in a readable format.

Main Function

def main(): voting_machine = VotingMachine('candidates.txt') # Initialize the


voting machine with the candidates file

Creates an instance of VotingMachine, loading candidates from candidates.txt.

voting_machine.display_candidates() # Display the list of candidates

Calls the method to show the available candidates.

while True:

Starts an infinite loop to allow multiple voters to cast their votes.

voter_id = input("Enter your voter ID (or 'exit' to quit, 'end' to finalize


voting): ")

Prompts the user to enter their voter ID, with options to exit or end voting.

if voter_id.lower() == 'exit': # Exit the loop if the user types 'exit' break elif
voter_id.lower() == 'end': # Finalize voting if the user types 'end' break
Checks for user input to either exit the program or end voting, breaking the loop
if either is typed.

candidate_number = input("Enter the number of the candidate you want to vote for:
")

Prompts the user to enter the candidate number they wish to vote for.

voting_machine.vote(voter_id, candidate_number) # Cast the vote

Calls the vote method to register the user's vote.

except Exception as e: print(f"Error: {e}") # Print any errors that occur

Catches and prints any exceptions that occur during voting.

voting_machine.display_results() # Display the final results

After exiting the loop, calls the method to display the final vote counts.

Entry Point

if __name__ == "__main__": main() # Execute the main function

Checks if the script is run directly (not imported) and calls the main function to
start the program.

You might also like