【问题标题】:Python return statement, frequent issuePython return 语句,常见问题
【发布时间】:2018-10-28 11:02:43
【问题描述】:

下面的程序查找像 code/cope/coje 等单词并返回匹配数。但是我的返回函数没有给我一个输出。 print(len(matches)) 给出了正确的输出,但我需要使用 return。我在this question 中看到 'findall' 是一种更直接的方法,但我现在想使用 finditer。为什么这个返回语句不正确?当我编写程序来学习 python 时,我实际上经常面临这个问题。我无法从这些参考文献中找到答案 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) 没有返回任何内容,也没有返回错误。见这里:repl.it

【问题讨论】:

  • 您的 return 语句看起来不错,但实际上您并没有在任何地方调用该函数。
  • “我无法选择答案” .... 选择东西不是你学习的方式。顺便问一下,这是你的代码吗?如果您能够自己定义一个函数,那么您应该知道需要调用该函数才能运行。 Python 没有“主要”概念。
  • 此代码返回找到的匹配数。我们需要更多的代码来演示这个问题。你说,“print() 有效”,那是什么意思?

标签: python-3.x return


【解决方案1】:

您的功能似乎运行良好。这是我在本地 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

它没有在repl.it 中输出任何东西,因为你没有发送任何东西来输出。将最后一行替换为 print count_code(mystr) 并查看结果:

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

这是我的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)

【讨论】:

  • 冒着听起来很愚蠢的风险。我在 Jupyter Notebook 中运行了相同的程序(只有返回函数),它显示了一个输出。但是 repl 只显示带有打印的输出。这是什么?要了解输出显示方式之间的区别,我必须知道什么。
猜你喜欢
  • 2013-06-14
  • 2010-09-24
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 2010-12-09
  • 2011-03-30
  • 1970-01-01
相关资源
最近更新 更多