2015-04-01 125 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)