代码允许我输入超过六次,而且它不会打印else
语句。我的代码是:
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ('AHOY! I am the Dread Prites Roberts , and i have a secret!')
print ('It is a number from 1 to 99. I\'ll give you 6 tries ')
while guess != secret and tries < 6:
guess = int(input('What is your guess? '))
if guess < secret:
print ('Too Low, you scurvy dog!')
elif guess > secret:
print ('Too high, boy')
tries = tries + 1
elif guess == secret:
print ('Avast! you got it ! Found my seceret , you did!')
else:
print ('No more guess! Better Luck next time')
print ('The secret number was',secret)
我在Python 3.4中尝试了代码。它打印结果超过六次。虽然猜测不等于秘密并且尝试...在6次尝试之后它将打印'No more guess better luck next time'
但是一次又一次地执行
答案 0 :(得分:4)
你有一个缩进问题(我想通过粘贴发生)但你的主要问题是,当猜测太高时你只是递增tries
。你也应该将最后一个if if移出while块,因为while条件已经处理了vars。
您的实施应如下所示:
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ('AHOY! I am the Dread Prites Roberts , and i have a secret!')
print ('It is a number from 1 to 99. I\'ll give you 6 tries ')
while guess != secret and tries < 6:
guess = int(input('What is your guess? '))
tries = tries + 1
if guess < secret:
print ('Too Low, you scurvy dog!')
elif guess > secret:
print ('Too high, boy')
if guess == secret:
print ('Avast! you got it ! Found my seceret , you did!')
else:
print ('No more guess! Better Luck next time')
print ('The secret number was',secret)