Python 自定义延迟打印函数作input参数时输出多余None的解决方案
问题根源
出现None输出是函数返回值和input()的参数逻辑不匹配导致的:
input(print_with_delay("xxx"))这类写法会优先执行括号里的print_with_delay(),由于函数内部没有定义return语句,运行结束后默认返回Noneinput()会把接收到的参数作为控制台提示文本打印出来,等延迟打印完那句对话提示后,光标停留的位置会额外输出None,用户后续输入的内容会紧跟在None后面,最终出现示例里的NoneTim、NoneY这类错位效果。
如果直接给函数补上return text的语句,还会出现重复打印的问题:函数本身已经在内部通过print(text)输出了一次提示文本,input拿到返回的文本后,又会把文本当提示再打印一遍,同一句话会出现在控制台两次。
修复方案
调整print_with_delay()的逻辑,兼顾普通场景下的延迟打印功能,和作为input提示参数使用时的需求:给函数加一个开关参数,当需要把文本传给input使用时,跳过内部的print操作,直接把延迟后的文本返回给input,既避免重复打印,也从根源上杜绝None输出。
修改后的完整可运行代码:
import time # Delay text function to create realism for console dialogues # Counts the length of the string and applies this to the delay # Greatly improves visibility in the code # No more time.sleep() between all print dialogues def print_with_delay(text, for_input=False): delay = len(text) / 100 + 1.2 time.sleep(delay) # 给input传参时不自行打印,把文本返回给input处理 if for_input: return text # 普通调用场景下正常打印延迟文本 print(text) def start_game(): # 传参时标记为input使用场景 username = input(print_with_delay("Hello adventurer, I am Tony Tales, and what is your name?", for_input=True)) print_with_delay(f"Nice to meet you {username}.") print_with_delay("They call me Tony Tales, because I am a very talented tale teller.") create_story = input(print_with_delay("I can sense greatness from you. Would you like to create a story with me? [Y/N]", for_input=True)) if create_story == "y" or create_story == "Y": print_with_delay("Great!") else: print_with_delay("Oooh? That is disappointing. Here, take this!") print_with_delay("Tony Tales stabs you with a Pointy Pen...") print_with_delay("You feel dizzy and faint...") print_with_delay("The story ended.") exit() # 启动游戏流程 start_game()
修改后的运行效果:
- 普通对话场景的延迟打印效果和原代码完全一致
- 等用户输入的提示文本会在延迟结束后紧跟在光标位置显示,没有多余的None,不会重复打印提示句
- 用户输入的内容会紧跟在提示文本后面,不会出现错位的输出。
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

