我寫了一個遊戲,玩家試圖猜測一個隨機數(參見下面的代碼)。還提供了諸如'太低...'和'太高...'的建議。但是如何扭轉它並讓計算機猜出玩家選擇的數字呢?我有這個困難,我不知道爲什麼。我想我需要從某人那裏'推',但不需要實際的代碼,因爲我需要自己嘗試。如果有人能幫助我,我將不勝感激。如何在python中編寫一個反向的「猜數字」遊戲?
這裏就是玩家要猜數的代碼(Python 3中):
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")
感謝您的幫助。
謝謝,但我還沒有學會名單運作方式呢。我怎樣才能做到沒有列表? – fdama
@fdama - 這就是我最後一段的解釋。 – mgilson