0

Sorry, just started learning python and this practice question is totally throwing me. I don't even know where to start, so any explanation would be much appreciated.

Create a function called average_age which takes two parameters:

  • members, a list of tuples
  • gender, a text string such as (but not limited to) 'M' or 'F'.

It should return the average age of entries in members whose gender matches the argument given for gender. If no matches are found, return the string 'No matches found.'

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

Then the code box starts with:

def average_age(members, gender): 

I tried:


names = []
def average_age(members, gender):
    for a in members:
        if a[2] == gender:
            names.append(a[0])
            print(names)

This is as far as I got with it, I expected the names to be printed in a list on one line. But when testing it with 'average_age(people, 'M')' instead they were printed like this:

['John']
['John', 'Ahmed']

I'm a new beginner and already very bad at picking this up so any help is appreciated!

Paul Dempsey
  • 639
  • 3
  • 19
tobs99
  • 1
  • You can start by tagging your python questions with the "python" tag, and formatting your code as code blocks. See [How do I format my posts?](https://stackoverflow.com/help/formatting) – Paul Dempsey Feb 18 '23 at 01:14
  • Try to change the last line to ```return names``` and put it out side of the for-loop. – Daniel Hao Feb 18 '23 at 02:34
  • Welcome to Stack Overflow. "I expected the names to be printed in a list on one line." Think carefully about the logic of the code. The *last* print that you see is the result that you wanted, right? So. When you call the function, **how many times** should it print? Just once, or repeatedly every time that a name is appended? Therefore, should that `print` code be inside the loop, or outside? Anyway, please try to ask questions more clearly, and keep in mind that this is **not a discussion forum**. The problem you are apparently trying to solve, does not match the one in the assignment. – Karl Knechtel Feb 18 '23 at 11:37

0 Answers0