2016-02-12 46 views
3
import random 

guesses = 3 
number = random.randint(1, 10) 
print (number) #<- To test what number im supposed to write. 

while guesses > 0: # When you have more than 0 guesses -> guess another number 
    guess = input("Guess: ") 

    if guess == number : # If guess is equal to number -> end game 
     print ('Your guess is right!.') 
     break 


    if guess != number : # If not number -> -1 guess 
     print ("Nope!") 
     guesses -= 1 

    if guesses == 0: #If all 3 guesses are made -> end game 
     print("That was it! Sorry.") 
     print(number,"was the right answer!") 

我在做什麼錯? 我想不出來,我希望你能幫助^ -^爲什麼這段代碼無法正常工作(我剛接觸編程,python)

如果你能教我如何改善我的編程,然後隨時寫我如何做到這一點!我打開學習新的東西btw對不起,我的英語不好:3(編輯:當我猜對了正確的數字,它仍然說「沒有!」,我不得不猜測另一個數字。)

+2

什麼不起作用?你期望什麼作爲輸出,什麼是實際輸出? – k4ppa

+1

當我猜想正確的數字,它仍然說,猜測是錯誤的,所以我不知道什麼是錯的。 – Venx

+1

這看起來像Python3。如果是這樣,請使用'guess = int(input(「Guess:」))'。 – bernie

回答

2

這看起來像Python3。如果是這樣,請改用guess = int(input("Guess: "))

在Python3中input()返回一個字符串,並將該字符串與一個永遠不會工作的整數進行比較。因此,將input()的返回值轉換爲一個整數,以確保您將蘋果與蘋果進行比較。

+1

你應該在那裏放一點點信息。例如,他應該確保輸入*可以轉換爲整數。否則,他會在半小時後回到這裏,問「爲什麼這段代碼不工作?」 – zondo

+1

謝謝@zondo。我會補充一點。 – bernie

0

你需要把int類型輸入的前面,所以:

guess = int(input("Guess: ")) 

這將轉向的猜測成一個整數,所以代碼識別它。

+0

這個問題已經有類似的答案 –

0

input()命令返回一個字符串,並且字符串不等於一個數字("3" == 3的計算結果爲false)。您可以使用int(...)函數將字符串(或浮點數)轉換爲整數。

我假設你使用Python 3.x,因爲print是一個函數。如果您使用的是Python 2.x,則應該使用raw_input(),因爲input()會導致解釋程序將Python代碼輸入並執行它(如eval(...)函數那樣)。

在99.999%的所有情況下,你要做而不是想要執行用戶輸入。 ;-)

+0

這個問題已經有類似的答案 –

-1

您的程序需要的另一個相當重要的事情是提示用戶,讓他們知道他們將如何處理您的程序。我已經相應地添加了提示。

import random 

print ("Hello. We are going to be playing a guessing game where you guess a random number from 1-10. You get three guesses.") 
number = random.randint(1, 10) 
# print (number) #<- To test what number im supposed to write. 
guesses = 3 
while guesses > 0: # When you have more than 0 guesses -> guess another number 
    guess = input("Enter your guess: ") 

    if guess == number : # If guess is equal to number -> end game 
     print ('Your guess is right!.') 
     break 


    if guess != number : # If not number -> -1 guess 
     print ("Nope!") 
     guesses -= 1 

    if guesses == 0: #If all 3 guesses are made -> end game 
     print("That was it! Sorry.") 
     print(number, "was the right answer!") 
相關問題