Python单词搜索程序结果正确但额外输出一行(None)问题求助
问题解答
错误原因
- 你定义的
search函数仅在内部执行打印逻辑,没有显式声明返回值,Python中所有未指定return内容的函数,默认会返回None - 最后一行代码使用
print(search(text, word))调用函数时,会先执行search内部的打印输出匹配结果,再打印函数的返回值None,因此会多出一行无意义的None输出
修复方法
两种方案二选一即可:
方案1:直接调用函数,无需额外套print
修改后代码如下:
def search(text, word): if word in text.split(): print('Word found') else: print('Word not found') text = input() word = input() # 直接执行函数即可,内部已经自带打印逻辑 search(text, word)
方案2:修改函数返回匹配结果,再统一打印
修改后代码如下:
def search(text, word): if word in text.split(): return 'Word found' else: return 'Word not found' text = input() word = input() print(search(text, word))
内容的提问来源于stack exchange,提问作者SkiesLearns
相关产品推荐
相关产品推荐

