Python Age Calculator: Build Your Own with Source Code

Faraz

By Faraz - May 17, 2023

Learn how to create a Python age calculator from scratch. Follow our step-by-step guide, complete with source code examples, and start calculating ages effortlessly.


Python Age Calculator.jpg

Python is a versatile programming language that offers a wide range of applications. One useful application is calculating age based on a given date of birth. In this article, we will explore a Python age calculator source code that enables users to calculate their age quickly and effortlessly.

Table of Contents

  1. Introduction to Python Age Calculator
  2. Importance of Age Calculation
  3. Understanding the Source Code
  4. Step-by-Step Guide to Using the Age Calculator
  5. Conclusion

Introduction to Python Age Calculator

Age calculation plays a crucial role in various fields, including healthcare, legal matters, and demographic analysis. Python, with its simplicity and powerful libraries, provides an ideal platform to develop an age calculator.

Importance of Age Calculation

Age calculation is essential in numerous situations. From determining eligibility for certain benefits to complying with legal requirements, accurate age calculation is paramount. Python's age calculator simplifies this process, allowing users to calculate age with ease.

Understanding the Source Code

To develop the Python age calculator, we need a few essential libraries. The datetime library provides functions to work with dates, while the tkinter library is used for creating graphical user interfaces (GUIs).

The source code consists of a function that takes the user's date of birth as input and returns their age. It calculates the difference between the current date and the provided date of birth, taking into account leap years and varying month lengths.

Step-by-Step Guide to Using the Age Calculator

1. Installing Python and IDE

To get started, install Python from the official website (https://www.python.org) and choose an integrated development environment (IDE) such as PyCharm, Visual Studio Code, or Jupyter Notebook.

2. Setting Up the Development Environment

After installing Python and the preferred IDE, set up a new project or create a new Python file. Make sure to import the necessary libraries by including the following lines of code:

import tkinter as tk
from datetime import date

3. Writing the Source Code

Next, define the function that will calculate the age based on the provided date of birth.

# import libraries

import tkinter as tk
from datetime import date

# GUI App class
class App:
    def __init__(self):
        # initialized window
        self.master = tk.Tk()
        self.master.geometry('280x300')
        self.master.configure(bg="lightblue")
        self.master.resizable(0, 0)
        self.master.title('Age Calculator')
        self.statement = tk.Label(self.master)

    def run(self):
        # creating a label for person's name to display
        self.l1 = tk.Label(text="Name: ", font="courier 10", bg="lightblue")
        self.l1.grid(row=1, column=0)
        nameValue = tk.StringVar()

        # creating a entry box for input
        self.nameEntry = tk.Entry(self.master, textvariable=nameValue, relief="solid")
        self.nameEntry.grid(row=1, column=1, padx=10, pady=10)

        # label for year in which user was born
        self.l2 = tk.Label(text="Year: ", font="courier 10", bg="lightblue")
        self.l2.grid(row=2, column=0)
        yearValue = tk.StringVar()
        self.yearEntry = tk.Entry(self.master, textvariable=yearValue, relief="solid")
        self.yearEntry.grid(row=2, column=1, padx=10, pady=10)

        # label for month in which user was born
        self.l3 = tk.Label(text="Month: ", font="courier 10", bg="lightblue")
        self.l3.grid(row=3, column=0)
        monthValue = tk.StringVar()
        self.monthEntry = tk.Entry(self.master, textvariable=monthValue, relief="solid")
        self.monthEntry.grid(row=3, column=1, padx=10, pady=10)

        # label for day/date on which user was born
        self.l4 = tk.Label(text="Day: ", font="courier 10", bg="lightblue")
        self.l4.grid(row=4, column=0)
        dayValue = tk.StringVar()
        self.dayEntry = tk.Entry(self.master, textvariable=dayValue, relief="solid")
        self.dayEntry.grid(row=4, column=1, padx=10, pady=10)


        def check_year():
            #simple method to check the validity of a user input birth year
            self.statement.destroy()
            today = date.today()
            try:
                year = int(self.yearEntry.get())
                if today.year - year < 0:
                    self.statement = tk.Label(text=f"{nameValue.get()}'s age cannot be negative.", font="courier 10", bg="lightblue")
                    self.statement.grid(row=6, column=1, pady=15)
                    return False
                else:
                    return True
            except Exception as e:
                self.statement = tk.Label(text=f"{nameValue.get()}'s birth year cannot parse to int.", font="courier 10", bg="lightblue")
                self.statement.grid(row=6, column=1, pady=15)
                return False

        def check_month():
            #simple method to check the validity of a user input birth month
            self.statement.destroy()
            try:
                month = int(self.monthEntry.get())
                if month < 0 or month > 12:
                    self.statement = tk.Label(text=f"{nameValue.get()}'s birth month is outside 1-12.", font="courier 10", bg="lightblue")
                    self.statement.grid(row=6, column=1, pady=15)
                    return False
                else:
                    return True
            except Exception as e:
                self.statement = tk.Label(text=f"{nameValue.get()}'s birth month cannot parse to int.", font="courier 10", bg="lightblue")
                self.statement.grid(row=6, column=1, pady=15)
                return False
        
        def check_day():
            #simple method to check the validity of a user input birth day
            self.statement.destroy()
            try:
                day = int(self.dayEntry.get())
                if day < 0 or day > 31:
                    self.statement = tk.Label(text=f"{nameValue.get()}'s birth day is outside 1-31.", font="courier 10", bg="lightblue")
                    self.statement.grid(row=6, column=1, pady=15)
                    return False
                else:
                    return True
            except Exception as e:
                self.statement = tk.Label(text=f"{nameValue.get()}'s birth month cannot parse to int.", font="courier 10", bg="lightblue")
                self.statement.grid(row=6, column=1, pady=15)
                return False

        # defining the function for calculating age
        def ageCalc():
            self.statement.destroy()
            today = date.today()
            #adding some stuff for checking validity of inputs
            if check_year() and check_month() and check_day():
                birthDate = date(int(self.yearEntry.get()), int(
                    self.monthEntry.get()), int(self.dayEntry.get()))
                age = today.year - birthDate.year
                if today.month < birthDate.month or today.month == birthDate.month and today.day < birthDate.day:
                    age -= 1
                self.statement = tk.Label(text=f"{nameValue.get()}'s age is {age}.", font="courier 10", bg="lightblue")
                self.statement.grid(row=6, column=1, pady=15)

        # create a button for calculating age
        self.button = tk.Button(text="Calculate age", font="courier 12 bold", fg="white", bg="dodgerblue", command=ageCalc)
        self.button.grid(row=5, column=1)
        
        # infinite loop to run program
        self.master.mainloop()
        

if __name__ == '__main__':
    age_calc = App()
    age_calc.run()

4. Explanation of Source Code

Here's a breakdown of how the code works:

  1. The necessary libraries are imported:
    • tkinter: This library is used for creating the graphical user interface.
    • date from datetime: This library is used for working with dates.
  2. The App class is defined, representing the GUI application. It has the following features:
    • The constructor (__init__) initializes the main window of the application with specific dimensions, background color, and title.
    • The run method sets up the GUI elements, such as labels and entry boxes for the user to input their name and birthdate information.
  3. The check_year, check_month, and check_day functions are defined to validate the user's input for the birth year, month, and day, respectively. They check if the input is a valid integer within the expected range. If there is an error or the input is invalid, an appropriate error message is displayed using the Label widget.
  4. The ageCalc function is defined to calculate the age based on the user's input. It uses the date.today() function to get the current date and compares it with the user's birthdate. The calculated age is then displayed using the Label widget.
  5. The run method continues with the setup of the GUI by creating a button that calls the ageCalc function when clicked.
  6. Finally, an instance of the App class is created, and the run method is called to start the GUI application.

To summarize, this script creates a simple GUI application that allows the user to input their name and birthdate. When the user clicks the "Calculate age" button, the application calculates the age based on the current date and the provided birthdate, and displays the result on the screen.

Conclusion

In this tutorial, we learned how to build a Python age calculator from scratch. By leveraging Python's date manipulation capabilities, we were able to calculate a person's age based on their birth date. We covered the steps of obtaining user input, performing date calculations, and displaying the calculated age.

Furthermore, we explored error handling and input validation techniques to ensure the calculator can handle unexpected inputs gracefully. We also discussed potential enhancements such as calculating age in different units and accounting for leap years.

By following this tutorial, you now have the knowledge and skills to create your own age calculator in Python. This project not only helps you understand date manipulation concepts but also equips you with valuable skills for handling dates in real-world applications.

Now it's time to apply what you've learned and start building innovative applications that involve age calculations using Python. Enjoy exploring the possibilities and expanding your Python programming skills!

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺