我在codesters/python bc中编写代码,这是我的学校教我的,我正在尝试在点击按钮中编写代码。我最初在没有if语句的地方使用它,但是我意识到我可能需要点击两次,我尝试了两次,得到错误消息"local variable ' first_hit‘referenced assignment line: 32“if first_hit == True:
当我第一次点击点击按钮时,就会发生这种情况
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)
发布于 2021-01-10 03:35:13
通常,一个变量是局部的,这意味着一旦您进入一个新的作用域(在本例中是您的函数),Python将不会“看到”该变量。
要使您的变量可从所有作用域访问,您可以在第一次引用之前使用global first_hit
。
由于在使用全局变量时,您经常会遇到为变量查找新名称的问题,因此将相互引用的内容放在一个类中通常是一个好主意。
https://stackoverflow.com/questions/65646243
复制相似问题