-1

for the following question: Find a list of all of the names in the following string using regex. I have written this code:

import re
def names():
    simple_string = """Amy is 5 years old, and her sister Mary is 2 years old. 
    Ruth and Peter, their parents, have 3 kids."""
    names= re.findall("[A-Z][a-z]*", simple_string)
    print(names)
    print(len(names))
names()

It gives the correct output like this: **['Amy', 'Mary', 'Ruth', 'Peter'] , 4** However when I use this : **assert len(names()) == 4, "There are four names in the simple_string"** it gives me this error: **object of type 'NoneType' has no len()** I don't know where is the error in function names, can anybody help? note: I can't change the assert function, it's inside the question.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • `len(names)` not `len(names())` – jordanm Sep 25 '20 at 19:28
  • @G.Anderson I don't see how that question is related – jordanm Sep 25 '20 at 19:29
  • @jordanm because the function returns None implicitly, and I assume the OP is trying to return the length of the function output, not the length of the similarly named variable inside the function – G. Anderson Sep 25 '20 at 19:33
  • @jordanm you may be misunderstanding the question—OP is asking about something *outside the function* `names`, not referring to the *variable* `names` – JaonHax Sep 25 '20 at 19:35

3 Answers3

3

names() does not return anything, therefore len() will not work. Try adding return(names). I would also avoid using function names for variable names inside the function.

willb
  • 56
  • 4
1

While you are printing the output of names() to sys.stdout, you are not returning the value of your names variable that's within it, meaning that the function itself returns None. Add return names to the end of your function to make that other code work.

JaonHax
  • 336
  • 1
  • 8
0

You're calling len(names()) this is asking for the length of what the names function returns. It returns nothing, so you're getting the NoneType error message.