【问题标题】:name (?) is not defined名称 (?) 未定义
【发布时间】:2019-06-20 05:59:01
【问题描述】:

我是 Python 编程的初学者 使用 PyCharm 尝试练习功能,但返回以下错误:

名称“rflag”未定义 但我认为它的定义! 这是代码:

def searcher(word: str, text: str, num: int = 1):

   global startindex
   global size
   global rflag

   if num == 1 and text.count(word) == 1:
       startindex = text.find(word);
       size = len(word);
       rflag = "word start from " + str(startindex + 1) + " and end in " + 
       str(size + startindex)
   elif num > 1 and text.count(word) <= num:
       startindex = 0
       for i in range(num):
           startindex = text.find(word, startindex)
           size = startindex + len(word)
        rflag = "word start from " + str(startindex + 1) + " and end in " + 
        str(size + startindex)

    return rflag


result = searcher("shahab", "shahabshahabshahab", 2)
print(result)

完整的错误信息:

C:\Users\Shahab\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/Shahab/Desktop/searcher.py

Traceback(最近一次调用最后一次):

文件“C:/Users/Shahab/Desktop/searcher.py”,第 21 行,在 result = searcher("shahab", "shahabshahabshahab", 2) 文件“C:/Users/Shahab/Desktop/searcher.py”,第 18 行,在搜索器中 return rflag NameError: name 'rflag' is not defined

进程以退出代码 1 结束

缩进: code and indentation image

【问题讨论】:

  • 这段代码应该做什么?
  • 请修正你的缩进...
  • @Aran-Fey 没有什么只是练习的样本
  • @hiroprotagonist 图像添加缩进
  • 如果我们不知道它应该做什么,我们无法修复您的代码...

标签: python function global-variables


【解决方案1】:

这将解决错误。

您只需在 if 条件之前初始化 rflag,因为这就是您要返回的内容

def searcher(word, text, num=1):
  rflag = ""
  if num == 1 and text.count(word) == 1:
    startindex = text.find(word);
    size = len(word);
    rflag = "word start from {} and end in {}".format(startindex+1, size+startindex)
  elif num > 1 and text.count(word) <= num:
    startindex = 0
    for i in range(num):
      startindex = text.find(word, startindex)
      size = startindex + len(word)
      rflag = "word start from {} and end in {}".format(startindex+1, size+startindex)
  return rflag

【讨论】:

  • 提前致谢!!如果我应该说,这是因为代码没有到达任何 if 或 elif 语句,所以不知道返回什么!但是你能帮我为什么在“shahabshahabshahab”甚至“shahab shahab shahab”中找不到任何“shahab”吗????
  • 在这个声明中searcher("shahab", "shahabshahabshahab", 2) 你的num=2,所以首先如果条件为假。同样,第二个 if 条件将为 false,因为 'shahabshahabshahab'.count('shahab') 返回 3 和 3 is NOT&lt;=2。这就是为什么searcher 不会返回任何东西的原因。如果你增加num searcher 会返回一些东西。
  • &lt;= 更改为 &gt;=
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2018-01-24
  • 2018-02-21
  • 2020-07-31
  • 2018-07-07
  • 2021-11-26
相关资源
最近更新 更多