在while循环中多次请求输入

2024-04-29 04:47:29 发布

您现在位置:Python中文网/ 问答频道 /正文

quit_game = "Goodbye, thank you for playing."

while True:
    tell_joke = print("Pete, Pete and Repeat went out on the lake in their boat. Pete and Pete fell out. Who is left in the boat? ")
    if input() == "REpeat":
        print(tell_joke)
        break
    elif input() == "Quit":
        print(quit_game)
    break;

每次用户输入“REpeat”时,我需要返回到原始的“tell_joke”语句,但是它要么打印新定义的输入,要么读取为无


Tags: andtheingameinputoutquitrepeat
2条回答

如果要在循环中循环,则应使用continue;如果要退出,则应使用break。在while循环中,您有一个break,因此它从不回圈。以下是我认为您需要的代码:

quit_game = "Goodbye, thank you for playing."
tell_joke = "Pete, Pete and Repeat went out on the lake in their boat. Pete and Pete fell out. Who is left in the boat?"
while True:
    option = input('What to do? 1. Repeat 2. Quit: ')
    if option.lower() == "repeat":
        print(tell_joke)
        continue
    elif option.lower() == "quit":
        print(quit_game)
        break
    else:
        print ("Invalid option provided..provide the right one")

输出:

What to do? 1. Repeat 2. Quit: bh
Invalid option provided..provide the right one
What to do? 1. Repeat 2. Quit: Repeat
Pete, Pete and Repeat went out on the lake in their boat. Pete and Pete fell out. Who is left in the boat?
What to do? 1. Repeat 2. Quit: Quit
Goodbye, thank you for playing.

while循环中,elif后面的break语句将始终执行,因此循环将只运行一次。为了避免这种情况,您可以简单地将break放在elif语句中;说到break,如果您希望在每次从输入中获取"REpeat"时重复该循环,那么您希望删除if语句中的break。此外,在您的代码中,输入被执行两次:第一次调用input()检查if条件,另一次检查elif条件。为了避免这种情况,循环中要做的第一件事是将用户输入保存到变量中

此外,要小心,因为每个周期(当输入"REpeat")调用print()函数两次,并将其返回值赋给tell_joke,然后再次调用print()函数来打印tell_joke变量,该变量包含print()的结果,这解释了“偶然的”None输出。为了防止多个无用的赋值,如果您不打算更改tell_joke的值,可以在整个循环之前,在quit_game字符串旁边声明并赋值。请记住,更清楚的是,仅使用这两个if语句,除了"REpeat""Quit"之外,您没有处理来自用户的任何其他输入,循环将只是重复本身

如果我正确理解您想要的输出,它应该是这样的:

quit_game = "Goodbye, thank you for playing."
tell_joke = "Pete, Pete and Repeat went out on the lake in their boat. Pete and Pete fell out. Who is left in the boat?"
while True:
    my_input = input()
    if my_input == "REpeat":
        print(tell_joke)
    elif my_input == "Quit":
        print(quit_game)
        break

如果您想更多地了解python中的控制流工具,我将您重定向到它们的documentation

相关问题 更多 >