Exercise
Hierarchical Structures
Objective
Develop a Python program to store two pieces of data for a person:
- Name
- Date of birth
The date of birth must be another NamedTuple consisting of day, month, and year.
Finally, create an array of persons, prompt the user for the data of two persons, and display them.
Example Python Exercise
Show Python Code
from collections import namedtuple
# Define the NamedTuple for Date of Birth
DateOfBirth = namedtuple('DateOfBirth', ['day', 'month', 'year'])
# Define the NamedTuple for Person
Person = namedtuple('Person', ['name', 'date_of_birth'])
# Create an array to store persons
persons = []
# Get data for the first person
name1 = input("Enter the name of the first person: ")
day1 = int(input("Enter the day of birth for the first person: "))
month1 = int(input("Enter the month of birth for the first person: "))
year1 = int(input("Enter the year of birth for the first person: "))
dob1 = DateOfBirth(day1, month1, year1)
person1 = Person(name1, dob1)
persons.append(person1)
# Get data for the second person
name2 = input("Enter the name of the second person: ")
day2 = int(input("Enter the day of birth for the second person: "))
month2 = int(input("Enter the month of birth for the second person: "))
year2 = int(input("Enter the year of birth for the second person: "))
dob2 = DateOfBirth(day2, month2, year2)
person2 = Person(name2, dob2)
persons.append(person2)
# Display the data of both persons
for i, person in enumerate(persons, 1):
print(f"Person {i}:")
print(f" Name: {person.name}")
print(f" Date of Birth: {person.date_of_birth.day}/{person.date_of_birth.month}/{person.date_of_birth.year}")
Output
Enter the name of the first person: John
Enter the day of birth for the first person: 15
Enter the month of birth for the first person: 5
Enter the year of birth for the first person: 1990
Enter the name of the second person: Alice
Enter the day of birth for the second person: 25
Enter the month of birth for the second person: 12
Enter the year of birth for the second person: 1985
Person 1:
Name: John
Date of Birth: 15/5/1990
Person 2:
Name: Alice
Date of Birth: 25/12/1985
Share this Python Exercise