python - 使用 "while"语句循环程序

标签 python loops while-loop

因此,我有一个程序,您必须在其中猜测一个数字,并且我对其进行了编码,以便该程序会告诉您您猜到的数字是高于还是低于真实数字。我的问题是程序在告诉用户猜测更高或更低之后结束。我想让程序循环,直到猜到我预设的数字,程序才会结束。这是我的代码:

    number = 10
    guess = int(input("Type in an integer: "))
    if guess == number:
        print ("Good Job!")
    elif guess < number:
        print ("The number is higher")
    else:
        print ("The number is lower")
    while guess!= number:
        print ("Try Again")
    print ("Done") 

我尝试使用 while 循环来循环程序,直到正确猜出数字,但“再试一次”脚本一直循环……感谢您的帮助!

最佳答案

您的流程控制设计不当,但您可以通过将代码包装在 while 循环中并应用 break once guess == number< 来修复。在 guess!=number 的其他情况下,循环会一直运行:

number = 10
while True:
    guess = int(input("Type in an integer: "))
    if guess == number:
        print ("Good Job!")
        break
    elif guess < number:
        print ("The number is higher")
    else:
        print ("The number is lower")
print ("Done")

您可以阅读有关 python 中的 while 循环的更多信息 here

关于python - 使用 "while"语句循环程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035459/

相关文章:

C++ While循环不迭代到文本文件中的下一行

c - 如何退出队列中的 while 循环?

php - Python:PHP "=="的等价物是什么

php - 如果类别的值为="",如何打破跳过循环?

python - Matplotlib 无法在 Python 3.5 上正确安装

c++ - 在循环中创建变量(当前循环索引作为它们的名称)

javascript - 重复字母表

c - 如何忽略输入中的 '\n'字符

python - 访问 iManage 上的文档

python - PM2 不记录 Python3 打印语句