0

I am taking a class on Python. I have this assignment and I keep getting UnboundLocalError and I don't understand why. The teacher made us do individual variables, no data storage. Here is my code:

import random 

times_rolled = input('Enter how many times you would like to roll the dice: ')

dice_roll2 = 0
dice_roll3 = 0
dice_roll4 = 0
dice_roll5 = 0
dice_roll6 = 0
dice_roll7 = 0
dice_roll8 = 0
dice_roll9 = 0
dice_roll10 = 0
dice_roll11 = 0
dice_roll12 = 0

def roll_dice():
    dice_roll = random.randint(2,13) 
    return (dice_roll)

def store_dice_roll(dice_roll):
    if dice_roll == 2: 
        dice_roll2 = dice_roll2 + 1 
    elif dice_roll == 3:
        dice_roll3 = dice_roll3 + 1
    elif dice_roll == 4:
        dice_roll4 = dice_roll4 + 1
    elif dice_roll == 5:
        dice_roll5 = dice_roll5 + 1
    elif dice_roll == 6:
        dice_roll6 = dice_roll6 + 1
    elif dice_roll == 7:
        dice_roll7 = dice_roll7 + 1
    elif dice_roll == 8:
        dice_roll8 = dice_roll8 + 1
    elif dice_roll == 9:
        dice_roll9 = dice_roll9 + 1
    elif dice_roll == 10:
        dice_roll10 = dice_roll10 + 1
    elif dice_roll == 11:
        dice_roll11 = dice_roll11 + 1
    elif dice_roll == 12:
        dice_roll12 = dice_roll12 + 1"""

for x in range(int(times_rolled)):
    dice_roll = roll_dice()
    store_dice_roll(dice_roll)

here is the error message

Exception has occurred: UnboundLocalError
  local variable 'dice_roll2' referenced before assignment
  File "/Users/emilysuranie/Desktop/python/dice.py", line 23, in store_dice_roll
    dice_roll2 = dice_roll2 + 1
  File "/Users/emilysuranie/Desktop/python/dice.py", line 51, in <module>
    store_dice_roll(dice_roll)

Any help would be appreciated!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    *The teacher made us do individual variables, no data storage.* -- your teacher is a sadist for making you copy and paste all of that stuff instead of just teaching you how lists work, IMO. But the solution is to move all those variable initializations inside the function where you use them. – Samwise Feb 24 '22 at 02:32
  • Welcome to Stack Overflow! I closed your question under an existing one that covers this exact same problem. But if there's anything still confusing you, LMK. Scoping is confusing, especially for newbies (including me at one point! :p ). Also, check out the [tour], and if you want tips for getting help in the future, see [ask]. – wjandrea Feb 24 '22 at 02:37

0 Answers0