下面的代码是我在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)
答案 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。