I'm trying to call a function which is contained inside of another function. I know that each of the interior functions work individually because I tested them prior to combining them in rollDice().
When I try to run the code, it consistently tells me that basically every variable (d20, d10, etc.) is undefined even though I have the rollDice() function running.
How can I get my interior function (d6(roll6)) to output the value that it's been assigned after having the rollDice(roll) function?
def diceRoll(roll):
def d20(roll20):
import random
roll20 = random.randint(1,20)
print("The roll is ", roll20)
return roll20
def d12(roll12):
import random
roll12 = random.randint(1,12)
print("The roll is ", roll12)
return roll12
def d6(roll6):
import random
roll6 = random.randint(1,6)
print("The roll is ", roll6)
return roll6
####### example of other part of code
def generateDungeon():
diceRoll(roll)
numberOfRooms = roll6
print("The roll was: ", roll6)
if numberOfRooms > 1:
print("There are ", numberOfRooms, "rooms in this dungeon.")
else:
print("There is only 1 room in this dungeon.")
return numberOfRooms
1 Answer 1
By executing the outer function, you aren't executing any of the inner functions. Their variables are out of scope, anyway.
If you really wanted to use a function in a function (which is unnecessary in this case, by the way), you could make your code much more succinct by using a closure. Also, it's easier just import your packages once at the top:
import random
def diceRoll(roll):
def helper():
r = random.randint(1, roll)
print("The roll is", r)
return r
return helper
Then, to use this, call the return value of diceRoll:
numberOfRooms = diceRoll(6)()
Note that this whole thing can be done like this:
def diceRoll(roll):
r = random.randint(1, roll)
print("The roll is", r)
return r
And called like:
numberOfRooms = diceRoll(6)
d6(), etc, so we cannot deduce what is going on. Furthermore we would need to see the exact text of the error message. And as a style note, you do not need to defineroll6, etc, as parameters.