总结陈述麻烦:数字猜谜游戏python

时间:2018-01-16 12:25:27

标签: python python-3.x python-2.7 if-statement

下面的代码是我在python中编写一个简单的数字猜谜游戏。 第一个版本完美无瑕。但是第二个,我只修改了关闭if语句导致语句后面的代码不能运行。任何人都可以解释原因吗?

有效代码

from random import randint
tries = 0
secret = randint(1,10)
for tries in range(5):
    guess=int(input("Try to guess the number between 1 and 10 that 
    I'm thinking of."))
    tries+=1
    if guess<secret:
        print("Guess higher!")
    elif guess>secret:
        print("Guess Lower!")
    else:
        print("Whoa!You got it right!The number I was thinking of 
        was %s and you guessed it in %s tries."%(secret,tries))
        break
if guess!=secret:
    print("Sorry,you\'re out of tries.The number was %s"%secret)

错误的代码

from random import randint
tries = 0
secret = randint(1,10)
for tries in range(5):
    guess=int(input("Try to guess the number between 1 and 10 that 
    I'm thinking of."))
    tries+=1
    if guess<secret:
        print("Guess higher!")
    elif guess>secret:
        print("Guess Lower!")
    else:
        print("Whoa!You got it right!The number I was thinking of 
        was %s and you guessed it in %s tries."%(secret,tries))
        break
if tries>5:
    print("Sorry,you\'re out of tries.The number was %s"%secret)

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

from random import randint
tries = 0
secret = randint(1,10)
for tries in range(5):
    guess=int(input("Try to guess the number between 1 and 10 that 
    I'm thinking of."))
    tries+=1
    if guess<secret:
        print("Guess higher!")
    elif guess>secret:
        print("Guess Lower!")
    else:
        print("Whoa!You got it right!The number I was thinking of 
        was %s and you guessed it in %s tries."%(secret,tries))
        break
    if tries == 5:
        print("Sorry,you\'re out of tries.The number was %s"%secret)

由于range将返回0到4之间的值,因此条件尝试&gt; 5永远不会得到满足。

答案 1 :(得分:0)

原因是range(5)评估为[0, 1, 2, 3, 4]

因此,tries永远不会超过5。

相关问题