2015-04-01 126 views
-2

该代码允许我输入六次以上,也没有打印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',但一次又一次地执行

回答

4

你有一个缩进问题(我猜是通过粘贴发生的),但你的主要问题是,你是当猜测过高时,只会递增tries。此外,你应该把最后一个动作移出while块,因为while条件已经在处理变量了。

你的实现应该是这样的:

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)