Skip to main content

Ex 11: Age Verification

Problem

We’re building a system to verify user age for access. The input will come as a string, which we must convert to a number before checking.

Rules

  • Define verify_age(age_str: str) -> str.
  • Convert the string to an integer using int().
  • Return "Access Granted" if the age is 18 or older.
  • Otherwise return "Access Denied".

Boilerplate

Copy below code and paste to our IDE for head start.

# Write our code inside this function
def verify_age(age_str: str) -> str:
pass # remove this

# Call with test data
print(verify_age("20"))
print(verify_age("16"))

Expected Output

Access Granted
Access Denied

Solution

Only view the solution after trying our best.

Show solution
def verify_age(age_str: str) -> str:
age = int(age_str)
return "Access Granted" if age >= 18 else "Access Denied"

# Test calls
print(verify_age("20"))
print(verify_age("16"))

Details

Using a ternary expression here ("Access Granted" if age >= 18 else "Access Denied") is the most Pythonic way to handle a simple binary choice. It keeps the logic on a single line without sacrificing readability.