2013-10-24 152 views
3

我有以Python編寫的代碼作爲一個項目。我已將計算機科學作爲GCSE。我對它很陌生,所以不知道如何解決這個錯誤。當我輸入我的第一個猜測,例如'5'時,它會說太高。然後一旦遊戲完成,它會說答案是7.這是一個我不斷嘗試解決但無法完成的錯誤。這裏是我用過的代碼:猜測遊戲錯誤?

import random 
numberofGuesses = 0 
print ("I'm thinking of a number between 1 and 10. What is it? You have three guesses.") 

while numberofGuesses < 3: 
    numberofGuesses = numberofGuesses +1 
    randomNumber = (random.randint(1,10)) 
    userInput = 0 
    userInput = input() 
    userInput = int(userInput) 
    if randomNumber > userInput: 
     print("Too Low! Try again") 
    if randomNumber < userInput: 
     print("Too High! Try Again") 

if numberofGuesses == 3: 
    print("Sorry! You lose. The correct number was:",randomNumber) 

if randomNumber == userInput: 
    print("Well Done! Your guess was correct!")` 

這段代碼和我提到的那個bug完全不同。

+1

下面的答案是正確的。只需要一個簡單的選擇,'userInput = 0'行就沒有必要了。 – sdasdadas

+0

你也應該看看退出循環時,他們猜對了,否則會讓他們再次猜測。 –

回答

7

您每次猜測時都重新選擇一個隨機數。相反,我相信你希望程序先選擇一個數字,然後輸入你的while循環。

randomNumber = (random.randint(1,10)) 

while numberofGuesses < 3: 

    numberofGuesses = numberofGuesses +1 

    userInput = 0 

    userInput = input() 

    userInput = int(userInput) 

    if randomNumber > userInput: 

     print("Too Low! Try again") 

    if randomNumber < userInput: 

     print("Too High! Try Again") 
1

您設置randomNumber與每個猜一個新的隨機數 - 所以對於第一個答案,這可能是7,然後你做一個猜測,並將其更改爲3。要解決這個問題,移動randomNumber = (random.randint(1,10))在你的while循環之外 - 做一次,而不是每個猜測一次。在你的學習中乾杯祝你好運!

3

有一個在每次迭代除了隨機數的重置另一個問題:

你不停止循環,如果猜測是正確的。你應該後增加的猜測計數器猜測的評估,否則你將無法告訴如果有人猜中的第三次嘗試:

import random 
numberofGuesses = 0 
randomNumber = (random.randint(1,10)) 
print("I'm thinking of a number between 1 and 10. What is it? You have three guesses.") 

while numberofGuesses < 3: 
    userInput = int(input()) 
    if randomNumber > userInput: 
     print("Too Low! Try again") 
    elif randomNumber < userInput: 
     print("Too High! Try Again") 
    else: # Correct guess! 
     break 
    numberofGuesses = numberofGuesses +1 
else: # Executed only if the while loop is not exited via "break" 
    print("Sorry! You lose. The correct number was:",randomNumber) 

if randomNumber == userInput: 
    print("Well Done! Your guess was correct!")