Check Eligibility to Vote in Python
Include age 18 and reject negative ages in a Python threshold exercise. New programmers separate invalid input from a failed eligibility rule at the boundary.
1# Program to check voting eligibility23age = int(input("Enter your age: "))45if age < 0:6 print("Age cannot be negative.")7elif age >= 18:8 print("You are eligible to vote.")9else:10 print("You are not eligible to vote yet.")
Output
You are not eligible to vote yet.
17 is non-negative but below 18, so the final branch runs.
In this one
- Include an age threshold with >=
- Handle invalid values separately
- Distinguish a teaching rule from a complete policy
How it works
- 1
Convert the age response with int.
- 2
Reject a negative age before applying the threshold.
- 3
Print eligible for age >= 18, otherwise print not eligible yet.
Edge cases
Boundary birthday
Enter 18.
Equality is included, so the eligible branch runs.
Negative age
Enter -1.
The invalid-age branch runs before either eligibility message.
What's going on
age >= 18 is the rule this exercise uses. The equality matters: an age of 18 is accepted, while 17 is not. Changing >= to > would shift the boundary by a year.
The first branch rejects negative ages before checking eligibility. A negative age is bad input, not simply someone who should wait a little longer. The elif and else then divide the remaining integer ages into two groups.
This demonstrates a numeric decision, not a complete legal eligibility check. Actual voting rules may also depend on citizenship, registration, jurisdiction, and dates. The program asks for completed age directly and does not calculate it from a birth year.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does age 18 pass?
Pick an answer to check it.
Question 2
Why test negative age first?
Pick an answer to check it.
Questions people ask
Does age 18 pass?
Yes. >= includes the threshold value itself.
Why test negative age first?
A negative age is invalid data and should not be labeled merely underage.
Does this establish legal eligibility?
No. It checks only the exercise age rule and omits other legal requirements.