Search code examples
pythonfunctionglobal-variables

name (?) is not defined


I'm beginner in Python programming using PyCharm trying to practice functions but it returns below error:

name 'rflag' is not defined but I think its defined! 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

Traceback (most recent call last):

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

Process finished with exit code 1

indentation: code and indentation image


Solution

  • This will solve the error.

    You just had to initialize rflag before if conditions, as that is what you're returning

    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