简而言之:
在我的程序结束时,需要比较两个结果在函数内部的整数。当我执行时,我得到未定义的变量错误。你知道吗
实际上:
我正在创建一个手蟋蟀python脚本,我们通常作为一个二重奏发挥。最后比较了对手的得分和最大的胜利。 带有变量的操作在函数内部,但在函数外部调用时,会显示未定义的变量错误。请帮忙?你知道吗
import random
while True:
pc_b_or_b = 0 #PC probability
#User Bowling module
def Bowl():
bat_PC = 0
User_bowl = 0
scoreofpc = 0
ScorePC = 0
while True:
bat_PC = random.randrange(1,11) #Random int gen
User_bowl = int(input("Your turn to bowl: ")) #int from user
if User_bowl<1 or User_bowl>10: #Fool proofing user must not keep less than 1 or gr8 than 10
print("Wrong number")
continue
if User_bowl == bat_PC: # Check if user == pc and out
print()
print("PC Out!")
print("PC Score:",scoreofpc)
break
else: #Continuation
print("Escape for PC. PC kept",bat_PC)
scoreofpc += bat_PC
print("Score:",scoreofpc)
ScorePC = scoreofpc
#User batting module
def User_Batting():
a = 0
score = 0
ManScore = 0
while True:
b = random.randrange(1,11) #Same as above but User is batting and pc randome int gen
a = int(input("Your turn to bat: ")) #But here if user int == pc then out for user
if a<1 or a>10:
print("Wrong number")
continue
if a==b:
print()
print("Out")
print("Score:",score)
break
else:
print("Escape! PC =",b)
score +=a
print("Score:",score)
ManScore = score
实际上,这里还有一些代码,我已经简化为StackOverflow所说的这些代码
这里的主要问题是,变量没有定义,所有其他模块工作正常
ScorePC1 = ScorePC
ManScore2 = ManScore
if ScorePC1 > ManScore2:
print("PC won the match by scoring",Score_of_PC)
elif ScorePC1 < ManScore2:
print("You won the match by scoring",User_Score)
else:
print("Your Score and PC score matched!")
quitter = input("Do you wanna Quit? Y/N? ")
if quitter == "yes" or quitter == "y" or quitter == "Y":
print("Thank You for playing!")
print("Script created by ***Techno-Sachin***")
quit()
elif quitter == "n" or quitter == "no" or quitter == "N":
print("Playing again..")
continue
else:
print("It's a wrong input. Try again")
期望:
最后,它将打印内部的语句if ScorePC1和ManScore2比较。你知道吗
错误:
The output is Big, but cut out to focus on the problem itself>
PC Out! PC Score: 38 Traceback (most recent call last): File "C:\Users\E.sachin\Documents\HTML5\Python Scripts\Hand_cricket20.py", line 164, in ScorePC1 = ScorePC NameError: name 'ScorePC' is not defined
变量
ScorePC
在函数Bowl()
内声明,这样变量的作用域就在Bowl()
内,这意味着不能从函数外部访问它。如果要在函数外部访问它,请在函数外部声明它,这不是一个好的设计。更好的设计是从函数返回值,比如@irfanuddin answer。你知道吗应该始终从函数返回值。在本例中,您可以从这两个函数返回
scoreofpc
和score
。您的代码如下所示:或者,可以使用全局变量。但它们是not advisable, infact, they're evil。你知道吗
尝试用
global ScorePC1
替换这个-ScorePC1 = ScorePC
,然后在任何地方引用它的名称ScorePC
来正常使用它。你知道吗在变量名之前使用global关键字会使变量的作用域成为全局的,因此可以从函数外部或内部访问变量。你知道吗
也可以在函数定义中使用
将它用于变量
ScorePC1
和ManScore
相关问题 更多 >
编程相关推荐