Maybe a stupid question but I’m new to python.
The following code throws an error:
deck = [10, 2, 5, 8, 2, 7]
deck_idx = 0
def deal():
card = deck[deck_idx]
deck_idx += 1
return card
print(deal())
Traceback (most recent call last):
File “main.py”, line 10, in
print(deal())
File “main.py”, line 6, in deal
card = deck[deck_idx]
UnboundLocalError: local variable ‘deck_idx’ referenced before assignment
while this doesn’t:
deck = [10, 2, 5, 8, 2, 7]
deck_idx = 0
def deal():
card = deck[0]
return card
print(deal())
10
both deck
and deck_idx
are declared in the same place, so I expect them to have the same visibility.
What am I missing here?