我正在为我的计算机科学GCSE制作骰子游戏,并且相对较新。当尝试有条件地将新变量分配给现有变量时,代码将运行直到输出新变量并返回名称错误为止。有人可以提出任何解决方案吗?
class player:
def __init__(self):
self.name = "foo"
if player1.score > player2.score:
winner = player1.name
elif player2.score < player1.score:
winner = player2.name
print(winner)
应该输出“ foo”,但给出名称错误:未定义名称“ winner”。
答案 0 :(得分:-1)
我想您是编码新手,否则这是一个愚蠢的错误。不用担心我来指导你
class player:
self.name = "foo"
elif player2.score < player1.score:
winner = player2.name
print(winner)
如果您清楚地看到自己的代码。您已经在elif中定义了赢家。这意味着它外面的代码不知道什么是“赢家”。因此,您需要在elif之外定义赢家。
winner = ''
class player:
self.name = "foo"
elif player2.score < player1.score:
winner = player2.name
print(winner)
答案 1 :(得分:-2)
尝试:
import random
class player:
def __init__(self, name):
self.name = name
self.score = random.randint(1,6)
print(self.name, self.score)
player_1 = player("Richard")
player_2 = player("Bob")
winner =''
if player_1.score > player_2.score:
winner = player_1.score
print(winner)
elif player_2.score> player_1.score:
winner = player_2.score
print(winner)
else:
print("Tie.")