在 while 循环内多次请求输入

Posted

技术标签:

【中文标题】在 while 循环内多次请求输入【英文标题】:Asking for input multiple times within a while loop 【发布时间】:2021-11-21 06:30:40 【问题描述】:
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”语句,但是它要么打印新定义的输入,要么读取为无。

【问题讨论】:

您需要获取一次输入并在 if 语句中使用它 如果你想重复,你不应该“打破”。我猜你想要“继续”。 【参考方案1】:

在您的while 循环中,break 语句在elif 之后将始终执行,因此您的循环将只运行一次。为避免这种情况,您可以简单地将break 放在elif 语句中;说到breaks,如果您想在每次从输入中获取"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。

【讨论】:

【参考方案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 循环内多次请求输入的主要内容,如果未能解决你的问题,请参考以下文章

C#在循环内多次重新初始化数组

利用switch语句:数字1—7分别表示周一到周日,随机输入数字后输出对应的星期

C语言while执行不了,代码见图?

第9课 循环语句与注释

如何修复具有多个返回错误的条件的while循环

综合练习题(if条件语句,while循环,奇数偶数