[英]Python error: UnboundLocalError: local variable 'score1' referenced before assignment
I am trying to make a simple dice roll game where two players roll a dice once for five rounds and the person with the highest score wins.我正在尝试制作一个简单的掷骰子游戏,其中两名玩家在五轮中掷一次骰子,得分最高的人获胜。
I have already tried setting the score1 variable to 0 within the function and outside of the function however this will cause the score to be reset to 0 every time.我已经尝试在函数内和函数外将 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
I want it to simply add the dice value to the score but I get this error :我希望它简单地将骰子值添加到分数中,但出现此错误:
UnboundLocalError: local variable 'score1' referenced before assignment
UnboundLocalError:赋值前引用了局部变量“score1”
You should use the global
identifier.您应该使用
global
标识符。
Some remarks about the code:关于代码的一些说明:
score2 = score2
.score2 = score2
。 Just don't do it. I modified your code and left some interesting features there, that will help you in the future and now.我修改了您的代码并在那里留下了一些有趣的功能,这将在未来和现在对您有所帮助。
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()
Next, try to make of those two functions one.接下来,尝试将这两个函数合二为一。
Use global
.使用
global
. Using a global
identifier is basically like calling it public
, meaning it can be accessed from all the other parts of the code.使用
global
标识符基本上就像调用它public
,这意味着它可以从代码的所有其他部分访问。 global score1
This is Just a very common question for Python.这只是 Python 的一个非常常见的问题。 Below is my answer in somewhere else.
下面是我在别处的回答。
global
and nonlocal
are very strange things when I was a beginner.当我是初学者时,
global
和nonlocal
是非常奇怪的东西。
Just think about it: why do we need them in Python?想想看:为什么我们需要在 Python 中使用它们?
It is because we don't need var
, let
and such similar things to declare variables.这是因为我们不需要
var
, let
类的东西来声明变量。
Think about Javascript
, it is dynamic script language too and very alike to python, but it needs var
or let
or const
to declare variables.想想
Javascript
,它也是动态脚本语言,与 python 非常相似,但它需要var
或let
或const
来声明变量。
The most important thing of declaring variables is to determine scope.声明变量最重要的是确定作用域。
So, in Python, our variables have implicit default scope: current scope where they are defined, and if we want to change scope of some variables, we need use global
or nonlocal
explicitly .因此,在 Python 中,我们的变量具有隐式默认作用域:定义它们的当前作用域,如果我们想更改某些变量的作用域,我们需要显式使用
global
或nonlocal
。
All names on the left side of =
mean to define variables. =
左侧的所有名称都表示定义变量。
Before executing code of some certain scope, Python will pre-compute all local variables
, which are those on the left side of =
.在执行某个范围的代码之前,Python 会预先计算所有
local variables
,即=
左侧的local variables
。 This is why you got UnboundLocalError: local variable 'X' referenced before assignment
in:这就是为什么你得到
UnboundLocalError: local variable 'X' referenced before assignment
的原因:
def foo():
X = X + 10
So, if we look up those names not in defined current scope, just follow the rules of scope chain: up, up, up and until built_in
.因此,如果我们在定义的当前作用域中查找那些名称,只需遵循作用域链的规则:向上、向上、向上和直到
built_in
。
Remember : scope of any name on the left side of =
is default current scope, and you have to assign it(bind something to it) before referring it.请记住:
=
左侧的任何名称的范围都是默认的当前范围,您必须在引用它之前为其分配(绑定某些内容)。
Global and local scope in python - Stack Overflow python中的全局和局部范围 - 代码日志
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.