它返回的錯誤是:Python的NameError,變「沒有定義」
NameError: name 'lives' is not defined
我知道代碼是不是儘可能地有效,這是我的第一個項目,但無論我嘗試做這個錯誤彈出,我試圖讓它成爲一個全球性的,但沒有幫助。我真的很感謝一些幫助,謝謝!
import random
import time
def main():
global guess,rand_num
win = False
rand_num = 45
lives = 10
while lives > 0 and win == False:
guess = int(input("Guess a number!"))
compare()
print("Well done!")
time.sleep(3)
def compare():
global lives,win
if guess == rand_num:
print("You guessed correct!")
win = True
elif guess > rand_num:
print ("Guess lower!")
lives = lives - 1
else:
print ("Guess higher!")
lives = lives - 1
def repeat():
replay = input("would you like to play again? Y/N")
if replay == "Y":
print("enjoy!")
main()
elif replay == "N":
"Goodbye then, hope you enjoyed!"
time.sleep(3)
os._exit
else:
print("please enter Y or N")
repeat()
main()
repeat()
編輯:把全球的生活裏面的main()返回錯誤:
UnboundLocalError: local variable 'lives' referenced before assignment
看看@ chepner的答案。 'global'聲明應該在'main'函數中。如果你這樣做,你的代碼工作正常。 – zondo
一般建議:避免全局變量。編寫函數,而不是程序。 Python程序員通常使用4個空格進行縮進。 –
我把所有4,生命,贏得,rand_num和猜測在全球比較()和主要(),似乎已經奏效,但我仍然不確定是否所有4都需要在兩個,或哪些是需要在哪裏。 @Zondo – Kaos