【问题标题】:How do I loop a gamequestion script until it is answered correctly? (Python)如何循环一个游戏问题脚本直到它被正确回答? (Python)
【发布时间】:2015-08-12 04:17:35
【问题描述】:
from random import randint
x=(randint(0,9))
print "I'm thinking of a number between 1 and 10."
y = raw_input("What is your number? (Integer from 1 to 10)")
if y<x:
    print "Too low!"
elif y>x:
    print "Too high!"
elif y==x:
    print "Spot On!"
    sys.exit()

我如何循环它,所以你必须不断猜测直到你得到数字?

【问题讨论】:

标签: python loops


【解决方案1】:

您可能需要为此目的调查while 循环。请查看the docs 了解详细信息,并查看答案already 以获取有用的代码片段。

【讨论】:

  • 通过使用while 循环,我能够让它工作。谢谢!
【解决方案2】:

当你得到正确的数字时就打破

from random import randint
x=(randint(0,10))
print "I'm thinking of a number between 1 and 10."
while True:
    y = int(raw_input("What is your number? (Integer from 1 to 10)"))
    if y<x:
        print "Too low!"
        print "Let's try again"
    elif y>x:
        print "Too high!"
        print "Let's try again"
    elif y==x:
        print "Spot On!"
        break

将 y 转换为 int,如果要包含 10,则必须在 randint 函数中迭代直到 10 而不是 9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多