break语句陷入循环

2024-07-04 05:28:45 发布

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

目标

使学生熟悉: -在循环中使用break语句; -在计算机代码中反映真实情况。在

场景

break语句用于退出/终止循环。 使用while循环,设计一个持续要求用户输入一个秘密单词的程序(例如,“你陷入了一个无限循环中!输入一个秘密单词来退出循环:“),除非用户输入“chupacabra”作为秘密退出词,在这种情况下,消息“You have successfully left the loop”应该打印到屏幕上,并且循环应该终止。 不要打印用户输入的任何单词。使用条件执行和break语句的概念。在

'''
Lab 2.2.22.1 - While loops with 'break' keyword use.
'''
secret_word = str(input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop."))
while secret_word != "chupacabra":
    print("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.")
    if secret_word == "chupacabra":
        print("You've successfully left the loop.")
'''
just keeps printing out both lines continuosly - in a loop.
'''

问题

当我运行这个程序时,它打印前2行并等待输入。如果输入与var匹配,它不显示“leftheloop”字符串,它什么也不做。如果我输入的不是正确的密文,它只会继续打印前两行的循环。在

我不知道如何使用while循环。我只想做两件事,如果输入不等于var,则打印A;如果输入与var匹配,则打印B。但是,我所读到的while循环的所有内容都是给while一些操作,然后if或elif或else都会得到其他的操作。在

我正在努力解决这个问题,因为我不知道如何编写这个循环,这样while不必做任何事情,这有意义吗?在

我在用python课程的自动取款机,所以请耐心等待。这不是任何考试或评分工作的一部分,但我宁愿先了解我做错了什么。在


Tags: the用户in程序loopyousecretvar
1条回答
网友
1楼 · 发布于 2024-07-04 05:28:45

您需要在循环中读取secret_word,并在匹配所需内容时使用break退出:

secret_word = ""
while True:
    secret_word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.")
    if secret_word == "chupacabra":
        print("You've successfully left the loop.")
        break

相关问题 更多 >

    热门问题