石头剪刀布,学校作业,python 3.7



为学校作业制作RPS游戏

import random
#player score
p1 = 0
p2 = 0
#add score
def AddScore(a,c):
print(a + " +1")
if c == "hum":
p1+=1
else:
p2+=1

#gets player choices
while p1 < 3 or p2 < 3:
print("Rock, Paper, Scissors, Shoot!")
a = int(input("Rock, Paper or Scissors? (1, 2, 3):"))
b = random.randint(1,3)
if a == b:
print("Draw!")
elif a > b and a != 1:
AddScore("Human", "hum")
elif a == 1 and b == 3:
AddScore("Human", "hum")
elif b > a and b != 1:
AddScore("Computer", "comp")
elif a == b and a == 3:
AddScore("Computer", "comp")
print(p1)
print(p2)

在第 9 行和第 21 行返回错误:

UnboundLocalError:赋值前引用的局部变量"p1">

出现错误的原因是AddScore内部的p1p2是局部变量,并绑定到该函数。但是,函数外部的p1p2是全局变量,但由于默认情况下函数中的每个变量都是局部变量,因此无法在函数内部访问它们。

您需要明确指示要在函数中使用p1p2全局变量。

def AddScore(a,c):
global p1, p2
print(a + " +1")
if c == "hum":
p1+=1
else:
p2+=1

您可能需要阅读以下有关函数作用域的文章:https://www.w3schools.com/python/python_scope.asp

这是一个范围问题。通过重新分配名称,Python 解释器保留重新分配的名称以供本地使用,从而从外部作用域中隐藏以前的值,这会导致如果在第一次分配之前使用名称,则会取消绑定该名称。

一个简单但非常不鼓励的解决方案是将p1p2显式设置为全局变量。

def AddScore(a,c):
global p1, p2
print(a + " +1")
if c == "hum":
p1+=1
else:
p2+=1

一个更干净的方法是询问并返回p1p2

def AddScore(a, c, p1, p2):
print(a + " +1")
if c == "hum":
p1+=1
else:
p2+=1
return p1, p2

用作:

p1, p2 = AddScore(..., ..., p1, p2)

最新更新