简体   繁体   English

名称(?)未定义

[英]name (?) is not defined

I'm beginner in Python programming using PyCharm trying to practice functions but it returns below error: 我是Python编程的初学者,使用PyCharm尝试练习函数,但它返回错误:

name 'rflag' is not defined but I think its defined! 名称'rflag'没有定义,但我认为它的定义! here is the code: 这是代码:

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)

full error message: 完整的错误消息:

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

Traceback (most recent call last): Traceback(最近一次调用最后一次):

File "C:/Users/Shahab/Desktop/searcher.py", line 21, in result = searcher("shahab", "shahabshahabshahab", 2) File "C:/Users/Shahab/Desktop/searcher.py", line 18, in searcher return rflag NameError: name 'rflag' is not defined 文件“C:/Users/Shahab/Desktop/searcher.py”,第21行,结果=搜索者(“shahab”,“shahabshahabshahab”,2)文件“C:/Users/Shahab/Desktop/searcher.py”,第18行,在搜索器中返回rflag NameError:未定义名称'rflag'

Process finished with exit code 1 进程以退出代码1结束

indentation: code and indentation image 缩进: 代码和缩进图像

This will solve the error. 这将解决错误。

You just had to initialize rflag before if conditions, as that is what you're returning 你必须在条件之前初始化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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM