声明了变量但未定义的错误显示在python中

时间:2019-09-07 04:39:21

标签: python python-3.x

简而言之:

在我的程序的最后,需要比较两个整数,它们的结果在函数本身内部。执行时,出现不确定的变量错误。

实际上是:

我正在创建一个手工板球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")   

期望:

如果比较ScorePC1和ManScore2,最后希望在其中打印语句。

错误:

  

输出很大,但切出重点放在问题本身上>

     

PC退出! PC得分:38追溯(最近通话记录):文件   “ C:\ Users \ E.sachin \ Documents \ HTML5 \ Python Scripts \ Hand_cricket20.py”,   第164行,在       ScorePC1 = ScorePC NameError:名称“ ScorePC”未定义

7 个答案:

答案 0 :(得分:0)

尝试将其-ScorePC1 = ScorePC替换为global ScorePC1,然后通过在任何地方引用其名称ScorePC来正常使用它。

在变量名称之前使用global关键字会使变量的作用域成为全局范围,因此可以从函数外部或内部访问变量。

也将相同的内容放入

之类的函数定义中
def Bowl():
   global ScorePC1

将其用于两个变量ScorePC1ManScore

答案 1 :(得分:0)

您应该始终从函数中返回值。在这种情况下,您可以从两个函数中返回scoreofpcscore。您的代码如下所示:

def bowl():
    #your code
    return scoreofpc

def user_batting():
    #your code
    return score

Score1 = bowl()
Manscore = user_batting()

或者,您可以使用全局变量。但是它们是not advisable, infact, they're evil

答案 2 :(得分:0)

如果精简代码位于主函数内,则问题在于未定义ScorePc变量,因为它是Bowl()函数内的局部变量,因为您在此进行了初始化。您无法访问其名称在main()函数中。 要解决此问题,您可以将其从Bowl()返回到ScorePc,也可以按照Himanshu所说将其设置为全局。

def Bowl():
    #code..
    return ScorePc
def main():
    ScorePc=Bowl()#this will store the returned value to ScorePc

def Bowl():
    global ScorePc

您可能应该阅读更多有关此的内容,以更好地了解其工作方式。 以下是一些链接: geeksforgeeks python documentation

答案 3 :(得分:0)

在函数ScorePC内声明变量Bowl(),这样做是为了使变量的范围在Bowl()内,这意味着不能从函数外部访问它。如果要在函数外部访问它,请在外部声明它,这不是一个好的设计。更好的设计是从@irfanuddin答案之类的函数返回值。

答案 4 :(得分:0)

这可以通过在函数中使用global关键字来完成。请参阅以下内容供您参考


def Bowl():
    global ScorePc
    ....

def User_Batting():
    global ManScore
    ....

但是,我建议从函数中返回值。如果您的函数带有多个值,则以数组形式返回。

答案 5 :(得分:0)

您已经在函数内部定义了 ScorePC ManScore ,事实证明,除非您执行以下两项操作之一,否则它们仅在该函数内部可用。

  1. 您可以使变量成为函数属性。 示例:

    def Bowl():
        Bowl.ScorePC = 0
    def User_Batting():
        User_Batting.ManScore = 0
    
  2. 您可以将变量设置为全局变量。 示例:

    def Bowl():
        global ScorePC
        ScorePC = 0
    def User_Batting():
        global ManScore
        ManScore = 0
    

如果要在其他文件中使用它们。您必须将文件导入到要使用的位置。 在这里,您会找到一些很好的例子:

Using global variables between files?

答案 6 :(得分:0)

我也做了一些修改。
    随机导入     def Bowl():         全球ScorePC         bat_PC = 0         User_bowl = 0         scoreofpc = 0         ScorePC = 0         而True:             bat_PC = random.randrange(1,11)#Random int gen             User_bowl = int(input(“您的转向碗:”))#int来自用户             如果User_bowl <1或User_bowl> 10:#傻瓜用户不得保留     小于1或gr8小于10                 打印(“数字错误”)                 继续             如果User_bowl == bat_PC:#检查user == pc并退出                 打印()                 打印(“ PC输出!”)                 打印(“ PC得分:”,scoreofpc)                 打破             否则:#Continuation                 打印(“ Escape for PC。保留了PC”,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

        # Main probem here, variable not defined
        # All other modules wotking perfectly
        ScorePC1 = ScorePC
        ManScore2 = ManScore

    if ScorePC1 > ManScore2:
        print("PC won the match by scoring",ScorePC1)
    elif ScorePC1 < ManScore2:
        print("You won the match by scoring", ManScore2)
    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***")
        exit()
    elif quitter == "n" or quitter == "no" or quitter == "N":
        print("Playing again..")
        play()
    else:
        print("It's a wrong input. Try again")

def play():
    Bowl()
    User_Batting()
play()