gpt4 book ai didi

Python 错误 : UnboundLocalError: local variable 'score1' referenced before assignment

转载 作者:行者123 更新时间:2023-11-28 17:59:00 24 4
gpt4 key购买 nike

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

我已经尝试在函数内和函数外将 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: local variable 'score1' referenced before assignment

最佳答案

您应该使用global 标识符。

关于代码的一些说明:

  1. 导入应该在代码的顶部。而且一个库导入一次就够了。
  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()

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

关于Python 错误 : UnboundLocalError: local variable 'score1' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com