-1
我剛剛開始使用python,我想知道爲什麼我的變量猜測沒有定義。我感覺好像是一個縮進問題,但是一旦我改變了縮進,我通常遇到語法錯誤,任何幫助理解這個問題都將不勝感激。NameError:猜測未定義
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
縮小我的朋友 – tinySandy
函數game()中的所有內容必須在該函數下縮進一致。您的while循環存在於該函數之外,並且猜測僅在該函數中有作用域。 –