Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning people born before certain year from tuple?

I need to write a function named older_people(people: list, year: int), which selects all those people on the list who were born before the year given as an argument. The function should return the names of these people in a new list.

An example of its use:

p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p4 = ("Ernest", 1997)
people = [p1, p2, p3, p4]

older = older_people(people, 1979)
print(older)

Sample output:
[ ‘Adam’, ‘Mary’ ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far I got:

    def older_people(people: list, year: int):

        for person in plist:
            if person[1] < year:
                return person[0]
 



    p1 = ("Adam", 1977)
    p2 = ("Ellen", 1985)
    p3 = ("Mary", 1953)
    p4 = ("Ernest", 1997)
    plist = [p1, p2, p3, p4]

    older = older_people(plist, 1979)
    print(older)

At the moment this just prints the first person (Adam) who is born before 1979.
Any help for this one?

>Solution :

First you should use the argument of the function in the body of older_people instead of the global variable plist. people should be used instead of plist.

Then, your return statement is inside the for loop, this means that it will leave the function at the first time the if condition is true, hence printing only one person.

def older_people(people: list, year: int):
    result = []
    for person in people:
        if person[1] < year:
         result.append(person[0])
    return result




p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p4 = ("Ernest", 1997)
plist = [p1, p2, p3, p4]

older = older_people(plist, 1979)
print(older)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading