0

I'm trying to use functions (something that I am inherently bad at apparentlyXD) and am trying to get the return statement info from the first and then use it in the second. Both are for rolling dice, so the first function is to have the first set returned, which is to be then used in the second function to give the user the option to reroll. What am I doing wrong in this implementation that it's not recognizing the original dieset list?

def rollDie():
   die1 = 2
   die2 = 2
   die3 = 2
   die4 = 4
   die5 = 5

   dieset = [die1,die2,die3,die4,die5]
   print(dieset)

   return dieset


def reRoll1():

rollDie() 
reroll1 = input("Would you like to reroll? Yes or No: ")
if reroll1 == "no":
    dieset = [die1,die2,die3,die4,die5]
else:
    count = 0
    times = int(input("How many die would you like to reroll? "))
    while count < times:
        whichreroll = input("Reroll die: ")
        if whichreroll == "1":
            die1 = random.randint(1,6)
        else:
            die1 
        if whichreroll == "2":
            die2 = random.randint(1,6)
        else:
            die2
        if whichreroll == "3":
            die3 = random.randint(1,6)
        else:
            die3
        if whichreroll == "4":
            die4 = random.randint(1,6)
        else:
            die4
        if whichreroll == "5":
            die5 = random.randint(1,6)
        else:
            die5
        dieset = [die1,die2,die3,die4,die5]
        count += 1
        print(dieset)   

        return dieset   
reRoll1()

It's telling me "local variable 'die1' referenced before assignment" but rollDie() comes first. If anyone could explain this to me it would be greatly appreciated:D

4

2 回答 2

0

您没有获得所需的行为,因为,die1不是全局变量,但您将它们视为全局变量。die2...

换句话说, inside与die1withinreRoll1()不同。die1rollDie()

为了得到你想要的,你应该使用返回值,或者通过在与你调用的地方相同的缩进级别上编写定义来全局初始化变量reRoll1()

于 2013-04-09T01:08:51.543 回答
0

为了能够引用从 rollDie() 返回的数据,您需要将其分配给一个变量,即:

dieset = rollDie() 

但是,您也有一个问题:

if reroll1 == 'no':
    dieset = [die1, die2, die3, die4, die5]

在这里,您引用了变量 die1、die2... 但尚未为它们分配任何值。

作为一种解决方法,您可以为这些变量分配一个任意值,例如 0:

dieset = [0, 0, 0, 0, 0]

但是...然后在您的条件中,您引用变量 die1, die2 ...; 实际上还没有分配。所以你可以忘记所有关于变量 dieset 的事情,并直接分配 die1, die2...:

die1, die2, die3, die4, die5 = rollDie() if reroll1 == 'yes' else [0, 0, 0, 0, 0]

这样,您就可以die1在以下条件中简单地引用值等。

希望这可以帮助

于 2013-04-08T23:18:06.863 回答