Create class voter and check eligibility

Create class voter and check eligibility

Create class Voter

  • Private variable : age
  • Method : set_age(a) → sets age if a>=18
  • Method : is_eligible() → returns True if age >= 18, else False
  • Create an object, set age, and check eligibility

class Voter:
    def __init__(self):
        # Private variable (name mangling)
        self.__age = 0

    def set_age(self, age):
        """Sets the age if it is 18 or more."""
        if age >= 18:
            self.__age = age
            print(f"Age set to {self.__age}.")
        else:
            print(f"Error: Age {age} is less than 18. Age must be 18 or above.")

    def is_eligible(self):
        """Returns True if age is 18 or more, else False."""
        return self.__age >= 18

# --- Creating an object and checking eligibility ---

# Object for a voter in India
voter1 = Voter()

print("--- Checking Eligibility for Voter 1 ---")
# Trying to set an ineligible age
voter1.set_age(17)
# Checking eligibility
print(f"Is eligible to vote? {voter1.is_eligible()}")

print("\n--- Checking Eligibility for Voter 2 ---")
voter2 = Voter()
# Setting a valid age (for a voter in Mumbai)
voter2.set_age(25)
print(f"Is eligible to vote? {voter2.is_eligible()}")