Search code examples
pythonuser-input

python repeats function 3 times


The purpose of this code is to:

  1. Ask the user to enter his name.
  2. Ask the user to enter his date of birth
  3. The code will split the name into first, middle and last name
  4. The code will calculate the age in years, months and days.
  5. The code will store all these data in a dictionary

Here is the code:

from datetime import datetime
from dateutil.relativedelta import relativedelta


    class Test:
        def __init__(self):
            self.today = datetime.today()
    
        def name(self):
            first_name, middle_name, last_name = input("enter your name:\n".title()).split(' ')
            return first_name, middle_name, last_name
    
        def age(self):
            date_of_birth = input("enter your date of birth:\n")
            date_of_birth = datetime.strptime(date_of_birth, "%d/%m/%Y")
            age = relativedelta(self.today, date_of_birth)
            return age
    
        def data(self):
            data = {"first name": self.name()[0],
                    "middle_name": self.name()[1],
                    "last name": self.name()[2],
                    "age years": self.age().years,
                    "age months": self.age().months,
                    "age days": self.age().days}
            print(data)
    
    
    Test().data()

The code makes no error.

But the question for the name and the age repeated three times for each. something like this

enter your date of birth:

26/9/1986

enter your date of birth:

26/9/1986

enter your date of birth:

26/9/1986


Solution

  • You are calling age() three times. You could call it once, and then access its members:

    def data(self):
        name = self.name()
        age = self.age()
        data = {"first name": name[0],
                "middle_name": name[1],
                "last name": name[2],
                "age years": age.years,
                "age months": age.months,
                "age days": age.days}
        print(data)