Calculate Age in Python Using int() | Python for Beginners
Calculate Your Age in Python Using int()
Learn how to take a user's birth year as input,
convert it from text to an integer using int(),
and calculate their approximate age.
What you'll learn
- How
input()receives user input - Why Python treats input as a string
- How to convert a string to an integer using
int() - How to use a variable in a calculation
- How to combine text and variables in
print()
Step 1: Ask for the user's name
name = input("What is your name? ")
The input() function displays a question and
waits for the user to enter something.
Step 2: Display a greeting
print("Hello " + name)
Here, the + operator joins the greeting
with the value stored in the name variable.
" " mean?
The space between quotation marks is a string containing one blank space.
Step 3: Ask for the birth year
birthyear = input("Enter your birth year: ")
The user's birth year is stored in the
birthyear variable.
Values received from input() are strings
by default, even when the user enters a number.
Step 4: Convert the birth year to an integer
birthyear = int(birthyear)
The int() function converts the value into
an integer so that Python can perform mathematical
calculations with it.
Step 5: Calculate the age
current_year = 2026
age = current_year - birthyear
The program subtracts the user's birth year from the
current year and stores the result in the
age variable.
This example calculates an approximate age based only on the birth year. The exact age also depends on whether the user's birthday has occurred this year.
Step 6: Display the result
print("Your age is:")
print(age)
Complete Python program
name = input("What is your name? ")
print("Hello " + name)
birthyear = input("Enter your birth year: ")
birthyear = int(birthyear)
current_year = 2026
age = current_year - birthyear
print("Your age is:")
print(age)
Example output
What is your name? Ali Hello Ali Enter your birth year: 2005 Your age is: 21
How does it work?
Gets information from the user.
Converts the birth year from a string into an integer.
The program subtracts the birth year from the current year.
Displays the result to the user.
Calculate Age in Python Using int() | Python for Beginners
Calculate Age in Python Using int() | Python for Beginners | Calculate Age in Python Using int() | Learn variables | input() Function | int() function, Python
Related
About this Python course
This Python course introduces beginners to programming through simple lessons, examples and step-by-step explanations.
The lessons gradually introduce Python concepts such as printing output, variables, data types, input, conditions, loops and other programming fundamentals.