[英]Python is saying that a variable has not been assigned when it has
import random
import time
name=input("Welcome to the game what is your name")
print(("This is a numbers game"),(name),("you will be playing against the computer."))
print("The idea of the game is to get closer to 21 to the computer without going over 21"),
ready="N"
ready=input("Are you ready to play the game yet?").lower
if ready=="yes" or ready=="y":
score=0
while (score)<21 and (ready == "Y" or ready == "Yes" or ready =="YES" or ready == "yes" or ready =="y"):
player1=random.randint(1,21)
score=(score+player1)
time.sleep(3)
print(("you have scored"),(score))
if score <21:
ready=input("Do you want to add more to your score?")
if score>21: *THE PROBLEMS ON THIS LINE HERE*
print("Sorry Over 21 , The Computer Wins!")
else:
print("ok Well done let us see what the computer can do with their turn")
computerscore=0
while(computerscore)<21 and (computerscore)<(score):
computer=random.randint(1,21)
computerscore=(computerscore+computer)
time.sleep(3)
print(("The computer has scored"),(computerscore))
if (computerscore)<=21 and (computerscore)>(score):
print("Sorry the computer wins")
else:
print("You win well done")
break
我收到一個錯誤,提示如果分數> 21:NameError:未定義名稱“分數”
但是我把score = 0定義了,不是嗎?
我猜您輸入的yes
正確的值,問題可能出在線路上-
ready=input("Are you ready to play the game yet?").lower
您要在ready
中將引用分配給lower
函數,而應該調用lower()
並在ready
分配返回值。 范例-
ready=input("Are you ready to play the game yet?").lower()
另外,如果您希望代碼正常工作,則當您不輸入ready
作為yes
,應在if
條件之前將score=0
設置為yes
if ready=="yes" or ready=="y":
可變score
在if
塊內聲明。
假設ready
與"yes"
和"y"
,則行score=0
永遠不會達到。
因此, if score>21:
會引發錯誤。
在輸入第一個if
條件之前,您必須設置一個默認值,例如score = 0
。
此外,您輸入了錯誤:
ready=input("Are you ready to play the game yet?").lower
您應該使用.lower()
調用該函數。
您需要使用if score>21:
行和隨后的所有內容,以便部分代碼包含在較高的if覆蓋范圍內。
import random
import time
name=input("Wecome to the game what is your name")
print(("This is a numbers game"),(name),("you will be playing against the computer."))
print("The idea of the game is to get closer to 21 to the computer without going over 21"),
ready="N"
ready=input("Are you ready to play the game yet?").lower
if ready=="yes" or ready=="y":
score=0
while (score)<21 and (ready == "Y" or ready == "Yes" or ready =="YES" or ready == "yes" or ready =="y"):
player1=random.randint(1,21)
score=(score+player1)
time.sleep(3)
print(("you have scored"),(score))
if score <21:
ready=input("Do you want to add more to your score?")
if score>21: *THE PROBLEMS ON THIS LINE HERE*
print("Sorry Over 21 , The Computer Wins!")
else:
print("ok Well done let us see what the computer can do with their turn")
#same with the rest
另外,此腳本可能有缺陷,因為有人輸入不同內容的可能性很大。 您可能要包括在該行中:
ready=input("Are you ready to play the game yet? Type 'Y' for Yes").lower()
有關您希望播放器專門放置的內容的更多文字。
但是,如上所述,要點是lower()
,這會導致錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.