B.E. PPS Unit 5 Practical 7 solution

Practical 7: Program to Subtract the DOB from Today's Date to Find Eligibility to Vote

Problem Statement

Write a Python program to subtract the Date of Birth (DOB) from today’s date to determine if a person is eligible to vote (age 18 or above).

Solution Code

				
					from datetime import datetime

# Function to check voting eligibility
def check_voting_eligibility(dob):
    today = datetime.today()
    age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
    
    if age >= 18:
        print("You are eligible to vote!")
    else:
        print("You are not eligible to vote yet.")

# Taking user input for DOB
dob_input = input("Enter your Date of Birth (YYYY-MM-DD): ")
dob = datetime.strptime(dob_input, "%Y-%m-%d")

# Checking voting eligibility
check_voting_eligibility(dob)

				
			

Output

The program should prompt the user to input their Date of Birth (DOB) in the format “YYYY-MM-DD”. After processing the input, it should display whether the user is eligible to vote based on their age.

Example Output

				
					Enter your Date of Birth (YYYY-MM-DD): 2005-02-19 You are eligible to vote!
Process finished with exit code 0
				
			

Explanation

  • User Input: The program prompts the user to enter their DOB in the format YYYY-MM-DD.
  • datetime.strptime(): Converts the string input into a datetime object for calculation.
  • Age Calculation: The program calculates the age by subtracting the birth year from the current year. It then adjusts the result if the birthday has not occurred yet in the current year.
  • Eligibility Check: If the calculated age is 18 or more, the user is eligible to vote.

 

Key Concepts Learned

  • Working with Dates and Times: Using datetime module for date calculations and comparisons.
  • User Input Handling: Capturing and processing input data from users.
  • Conditional Statements: Using if-else statements to make decisions based on the calculated age.
Tech Amplifier Final Logo