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
1 Answer 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)
returnstatement looks fine, but you're not actually calling the function anywhere.