我是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
回溯(最近通话最近一次):
文件“ C:/Users/Shahab/Desktop/searcher.py”,第21行,在 结果= searcher(“ shahab”,“ shahabshahabshahab”,2)文件“ C:/Users/Shahab/Desktop/searcher.py”,第18行,在searcher中 返回rflag NameError:未定义名称'rflag'
以退出代码1完成的过程
答案 0 :(得分:0)
这将解决错误。
您只需要在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