使用函数时输入returns None 延迟打印字符串

Input returns None when using function to print a string with a delay

这是我延迟打印的后续问题。但是这次我在尝试输入 print_with_delay(text) 函数时卡住了。它 returns 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):
    delay = len(text) / 100 + 1.2
    time.sleep(delay)
    print(text)
    # if not text:
    #    return text

def start_game():
    username = input(print_with_delay("Hello adventurer, I am Tony Tales, and what is your name?"))
    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]"))
    
    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()

输出:

Hello adventurer, I am Tony Tales, and what is your name?
NoneTim
Nice to meet you Tim.
They call me Tony Tales, because I am a very talented tale teller.
I can sense greatness from you. Would you like to create a story with me? [Y/N]
NoneY
Great!

start_game 的前两行替换为以下内容:

username = input("Hello adventurer, I am Tony Tales, and what is your name? ")
print_with_delay(f"Nice to meet you %s ." % username)

您需要从输入中删除 print_with_delay,因为它是 returns None

的函数

如@Chepner 所述,input() 方法不需要字符串参数。

它是这样工作的:

def start_game():
    print_with_delay("Hello adventurer, I am Tony Tales, and what is your name?")
    username = input()
    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.")
    print_with_delay("I can sense greatness from you. Would you like to create a story with me? [Y/N]")
    create_story = input()

我曾希望有另一种方法来修复它。但这暂时可以完成工作。

编辑:

上面显示的是解决方法。检查@Chepner 他的答案以获得更好的解决方案。

您可以编写一个单一的通用 with_delay 函数,该函数将 运行 一个 任意 函数,在延迟后使用给定的参数。你可以让它默认为 print 来模拟 print_with_delay.

def with_delay(text, f=print):
    delay = len(text) / 100 + 1.2
    time.sleep(delay)
    return f(text)


def start_game():
    username = with_delay("Hello adventurer, I am Tony Tales, and what is your name?", input)
    with_delay(f"Nice to meet you {username}.")
    with_delay("They call me Tony Tales, because I am a very talented tale teller.")
    create_story = with_delay("I can sense greatness from you. Would you like to create a story with me? [Y/N]")