1

The below program finds words like code/cope/coje etc. and returns the count of matches. However my return function is not giving me an output. print(len(matches)) gives the right output but I need to use return. I see in this question that 'findall' is a more straightforward method, but I want to use finditer for now. Why isn't this return statement correct? I'm actually facing this problem in frequently as I write programs to learn python. I was unable to pick the answer from these references one,two

import re
mystr = "codexxxcmkkaicopemkmaskdmcone"

def count_code (char):
  pattern = re.compile (r'co\we')
  matches = pattern.finditer(char)
  result = tuple (matches)
  return len(result)

count_code(mystr)

count_code (mystr) didn't return anything, and did not return an error. See here : repl.it

3
  • Your return statement looks fine, but you're not actually calling the function anywhere. Commented May 18, 2018 at 4:49
  • "I was unable to pick the answer" .... picking things is not how you learn. By the way, is this your code? If you were able to define a function on your own, you should know the function needs to be called to run. Python does not have a "main" concept. Commented May 18, 2018 at 4:51
  • This code returns the number of matches found. We need more code to demonstrate the problem. You say, "print() works", in what way is that? Commented May 18, 2018 at 4:53

1 Answer 1

1

Your function seems to work fine. This is what I get when I run it in a local repl:

>>> import re
>>> mystr = "codexxxcmkkaicopemkmaskdmcone"
>>>
>>> def count_code (char):
...   pattern = re.compile (r'co\we')
...   matches = pattern.finditer(char)
...   result = tuple (matches)
...   return len(result)
...
>>> count_code(mystr)
3

It isn't outputting anything in repl.it because you're not sending anything to output. Replace that last line with print count_code(mystr) and see the results:

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
>   
3
>   

And here's my repl.it.

import re
mystr = "codexxxcmkkaicopemkmaskdmcone"

def count_code (mystr):

    pattern = re.compile (r'co\we')

    matches = pattern.finditer(mystr)
    matches = tuple (matches)

    return len(matches)


print count_code(mystr)
Sign up to request clarification or add additional context in comments.

1 Comment

At the risk of sounding dumb. I ran the same program in Jupyter Notebook (with only return function) and it showed me an output. But the repl only shows an output with print. What is this? What do I have to know to understand the difference between how output is shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.