Write a python program to find the elder person of two persons using class & object


This Python program defines a Person class and a function find_elder to find the elder person among two given individuals based on their ages. Here's an explanation of the program:

  • class Person: This is the Person class with a constructor __init__ that initializes two attributes, name and age. It represents a person with a name and age.
  • def find_elder(person1, person2): This function takes two Person objects, person1 and person2, as parameters. It compares their ages and returns the elder person. If both persons have the same age, it returns None.
  • The program creates two Person objects, person1 and person2, representing two individuals with their respective names and ages.
  • The find_elder function is called with these two Person objects, and the result is stored in the elder variable.
  • The program then checks whether elder is None. If it's None, it means both persons have the same age, so it prints "Both persons are of the same age." Otherwise, it prints the name and age of the elder person.

When you run this program, it will determine which of the two people is older based on their ages and print the corresponding message. If both persons have the same age, it will indicate that both are of the same age. This program demonstrates how to define a class, create objects, and compare their attributes to make decisions based on the object's state.


Source Code

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
def find_elder(person1, person2):
    if person1.age > person2.age:
        return person1
    elif person2.age > person1.age:
        return person2
    else:
        return None
 
# Create two Person objects
person1 = Person("Sathish", 27)
person2 = Person("Pooja", 25)
 
# Find the elder person
elder = find_elder(person1, person2)
 
if elder is None:
    print("Both persons are of the same age")
else:
    print(f"Elder Person \nName : {elder.name} \nAge : {elder.age}")

Output

Elder Person
Name : Sathish
Age : 27

Example Programs