【问题标题】:Python error: UnboundLocalError: local variable 'score1' referenced before assignmentPython 错误:UnboundLocalError:赋值前引用了局部变量“score1”
【发布时间】:2019-11-03 02:55:48
【问题描述】:

我正在尝试制作一个简单的掷骰子游戏,其中两名玩家掷骰子一次,共五轮,得分最高的人获胜。

我已经尝试在函数内和函数外将 score1 变量设置为 0,但这会导致每次将分数重置为 0。

#setting the scores as 0 before.
score1=0
score2=0

def round1():
    print('Round 1, lets go')
    input("Player 1 press ENTER to roll dice")
    diceroll1()
    input("Player 2 press ENTER to roll dice")
    diceroll2()
    round2()
#Round 1, calls upon dice roll functions and.

#dice roll function for player 1
def diceroll1():
    import random
    number = random.randint(1,6)
    print("Your number is: " + str(number))
    if number % 2 == 0:
        number = number + 10
        score1 = score1 + number
        print("Your new score is: " + str(score1))
    else:
        number = number - 5
        score1 = score1 + number
        print("Your new score is: " + str(score1))
    if score1 < 0:
        score1 = 0
    else:
        score1=score1

#dice roll function for player 2
def diceroll2():
    import random
    number = random.randint(1,6)
    print("Your number is: " + str(number))
    score2
    if number % 2 == 0:
        number = number + 10
        score2 = score2 + number
        print("Your new score is: " + str(score2))
    else:
        number = number - 5
        score2 = score2 + number
        print("Your new score is: " + str(score2))
    if score2 < 0:
        score2 = 0
    else:
        score2=score2

我希望它简单地将骰子值添加到分数中,但我收到此错误:

UnboundLocalError: 赋值前引用了局部变量'score1'

【问题讨论】:

标签: python variables variable-assignment


【解决方案1】:

您应该使用global 标识符。

关于代码的一些说明:

  1. imports 应该在代码的顶部。一个库导入一次就够了。
  2. 您不必将变量的值重新定义为它自己的值。喜欢这个score2 = score2。只是不要这样做。
  3. 我建议您使用 while 循环来使游戏无限循环,或者使用 for 循环来实现 const 轮数。
  4. 检查您的代码并计算重复项。他们有很多。尽量减少数量。

我修改了您的代码并在那里留下了一些有趣的功能,这将在将来和现在对您有所帮助。

from random import randint


#setting the scores as 0 before.
score1=0
score2=0


#dice roll function for player 1
def diceroll1():
    global score1
    import random
    number = randint(1,6)
    print(f"Your number is: {str(number)}")

    number += - 5 if number % 2 else 10
    score1 += number

    if score1 < 0:
        score1 = 0

    print(f"Your new score is: {str(score1)}")


#dice roll function for player 2
def diceroll2():
    global score2
    import random
    number = randint(1,6)
    print(f"Your number is: {str(number)}")

    number += - 5 if number % 2 else 10
    score2 += number

    if score2 < 0:
        score2 = 0

    print(f"Your new score is: {str(score2)}")


def game_loop():
    for _ in range(int(input("Raound number: "))):
        print('Round 1, lets go')
        input("Player 1 press ENTER to roll dice")
        diceroll1()
        input("Player 2 press ENTER to roll dice")
        diceroll2()
        print()


if __name__ == "__main__":
    game_loop()

接下来,尝试将这两个功能合二为一。

【讨论】:

    【解决方案2】:

    使用global。使用global 标识符基本上就像调用它public,这意味着它可以从代码的所有其他部分访问。 global score1

    【讨论】:

    • 这应该用于任何其他类似性质的变量(score2、score3 等...)
    【解决方案3】:

    这只是 Python 的一个非常常见的问题。以下是我在其他地方的回答。

    globalnonlocal在我还是初学者的时候是很奇怪的东西。

    想一想:为什么我们在 Python 中需要它们?

    因为我们不需要varlet之类的东西来声明变量。

    想想Javascript,它也是动态脚本语言,与python非常相似,但需要varletconst来声明变量。

    声明变量最重要的是确定范围。

    因此,在 Python 中,我们的变量具有隐式默认范围:定义它们的当前范围,如果我们想更改某些变量的范围,我们需要显式使用 globalnonlocal。强>

    =左侧的所有名称都表示定义变量。

    在执行某个范围的代码之前,Python 会预先计算所有local variables,即= 左侧的那些。 这就是你得到UnboundLocalError: local variable 'X' referenced before assignment的原因:

    def foo():
        X = X + 10
    

    所以,如果我们查找那些不在定义的当前范围内的名称,只需 遵循作用域链的规则:向上、向上、向上直到built_in

    记住=左侧的任何名称的范围都是默认的当前范围,您必须在引用它之前对其进行分配(绑定一些东西)。

    Global and local scope in python - Stack Overflow

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-14
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 2012-11-14
      • 2013-11-29
      相关资源
      最近更新 更多