0

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

1 Answers1

0

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
ashish-ucsb
  • 101
  • 6
  • thanks in advance!! if I should say, its because code not reach at any if or elif statement so dont know return what! but can you help me why it can't find any "shahab" in "shahabshahabshahab" or even in "shahab shahab shahab" ???? – Shahab Ouraie Jun 20 '19 at 06:53
  • In this statement `searcher("shahab", "shahabshahabshahab", 2)` your `num=2`, so first if condition will be false. Similarly, second if condition will be false since `'shahabshahabshahab'.count('shahab')` returns 3 and `3 is NOT<=2`. That is why `searcher` will not return anything. If your increase `num` searcher will return something. – ashish-ucsb Jun 20 '19 at 06:59
  • changed `<= ` to `>= ` – Shahab Ouraie Jun 20 '19 at 07:09