首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我为了好玩而尝试编写21点代码,在赋值之前,我得到这个错误的本地变量'first_hit‘:32行

我为了好玩而尝试编写21点代码,在赋值之前,我得到这个错误的本地变量'first_hit‘:32行
EN

Stack Overflow用户
提问于 2021-01-10 02:37:26
回答 1查看 37关注 0票数 0

我在codesters/python bc中编写代码,这是我的学校教我的,我正在尝试在点击按钮中编写代码。我最初在没有if语句的地方使用它,但是我意识到我可能需要点击两次,我尝试了两次,得到错误消息"local variable ' first_hit‘referenced assignment line: 32“if first_hit == True:

当我第一次点击点击按钮时,就会发生这种情况

代码语言:javascript
运行
复制
first_hit = True
def click(hit_button):
    if first_hit == True:
        player3 = random.choice(cards)
        player3disp = codesters.Display(player3, 50, -150)
        player_total = player1 + player2 + player3
        playertotaldisp.update(player_total)
        first_hit = False
        stage.wait(1)
    elif first_hit == False:
        player4 = random.choice(cards)
        player4disp = codesters.Display(player4, 150, -150)
        player_total = player1 + player2 + player3 + player4
        playertotaldisp.update(player_total)
    
hit_button.event_click(click)
EN

Stack Overflow用户

发布于 2021-01-10 03:35:13

通常,一个变量是局部的,这意味着一旦您进入一个新的作用域(在本例中是您的函数),Python将不会“看到”该变量。

要使您的变量可从所有作用域访问,您可以在第一次引用之前使用global first_hit

由于在使用全局变量时,您经常会遇到为变量查找新名称的问题,因此将相互引用的内容放在一个类中通常是一个好主意。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65646243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档