0
0
PythonProgramBeginner · 2 min read

Python Program to Check Voting Eligibility

You can check voting eligibility in Python by getting the age input and using if age >= 18: to decide if the person can vote, like if age >= 18: print('Eligible to vote') else: print('Not eligible to vote').
📋

Examples

Input17
OutputNot eligible to vote
Input18
OutputEligible to vote
Input25
OutputEligible to vote
🧠

How to Think About It

To check voting eligibility, first get the person's age. Then compare the age with 18 using the >= operator. If the age is 18 or more, the person can vote; otherwise, they cannot.
📐

Algorithm

1
Get the age input from the user
2
Check if the age is greater than or equal to 18
3
If yes, print 'Eligible to vote'
4
Otherwise, print 'Not eligible to vote'
💻

Code

python
age = int(input('Enter your age: '))
if age >= 18:
    print('Eligible to vote')
else:
    print('Not eligible to vote')
Output
Enter your age: 20 Eligible to vote
🔍

Dry Run

Let's trace the input age 20 through the code

1

Input age

User enters 20, so age = 20

2

Check age >= 18

20 >= 18 is True

3

Print result

Print 'Eligible to vote'

StepAgeCondition (age >= 18)Output
120TrueEligible to vote
💡

Why This Works

Step 1: Get user input

We use input() to get the age as a string and convert it to an integer with int() so we can compare numbers.

Step 2: Compare age

The condition age >= 18 checks if the person is old enough to vote.

Step 3: Print eligibility

If the condition is true, print 'Eligible to vote'; otherwise, print 'Not eligible to vote'.

🔄

Alternative Approaches

Using a function
python
def check_voting_eligibility(age):
    return 'Eligible to vote' if age >= 18 else 'Not eligible to vote'
age = int(input('Enter your age: '))
print(check_voting_eligibility(age))
This approach organizes the logic inside a function for reuse and cleaner code.
Using ternary operator directly in print
python
age = int(input('Enter your age: '))
print('Eligible to vote' if age >= 18 else 'Not eligible to vote')
This is a concise way to write the check and print in one line.

Complexity: O(1) time, O(1) space

Time Complexity

The program runs in constant time because it only performs a single comparison regardless of input.

Space Complexity

The program uses constant space for storing the age and output strings.

Which Approach is Fastest?

All approaches run in constant time and space; using a function adds clarity but no performance difference.

ApproachTimeSpaceBest For
Simple if-elseO(1)O(1)Quick checks and beginners
Function-basedO(1)O(1)Reusable code and larger programs
Ternary operatorO(1)O(1)Concise one-liners
💡
Always convert input to integer before comparing ages to avoid errors.
⚠️
Forgetting to convert the input string to an integer causes incorrect comparisons.