jeudi 27 août 2020

Else statement to return text if no matches found - average from list

I have a list of people with names, age and gender:

people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]

I have written some code that pulls back the average age of all males ('M'):

def average_age(members,gender):
    return sum([member[1] for member in people if member[2] == "M"])/2

This returns the expected result:

average_age(people, 'M')
26.5

However, if I was to write average_age(people, 'Z') I would like it to return the result statement to return 'No matches found.' At the moment, it still returns 26.5.

I have tried putting an else statement within the code but nothing seems to work.

Any help would be greatly appreciated.

Thank you

Aucun commentaire:

Enregistrer un commentaire