0

For some reason I am getting an unresolved reference 'i' error here in python 3.9.x

How can I amend my code to get it to run without error?

 for card in range(len(cards)):
    card = cards[i]
    print(f"{i+1} - {card}")

# get choice
choice = get_int_input(1, len(cards))
# get card
return cards[choice-1] if choice else None

'''

rowan333
  • 15
  • 5
  • 4
    Take a look at your `for` loop. What is `i` _supposed_ to be? Where does it come from? Now take that `card = cards[i]` line out and see what happens. You are already creating `card` in your loop: `for card in...`. There's no need to index into `cards`. – ChrisGPT was on strike Jan 02 '21 at 18:42

3 Answers3

5

Python is right. You has not i variable. Where do you see it?

If cards contains 4 element, your card will take successively 0, 1, 2, 3. So change your for loop like that:

for i in range(len(cards)):
    card = cards[i]
    print(f"{i+1} - {card}")

But the best way to do what you want is like that:

for i, card in enumerate(cards):
    print(f"{i+1} - {card}")

enumerate function will create an iterable variable that contains tuples of (key, value). For example:

>>> print(list(enumerate(['a', 'b', 'c'])))
[(0, 'a'), (1, 'b'), (2, 'c')]

In the same example, this loop:

for i, letter in enumerate(['a', 'b', 'c'])

will take successively this variable: | iterations | i | letter | | ---- | ------ | ----- | | 1 | 0 | 'a' | | 2 | 1 | 'b' | | 3 | 2 | 'c' |

Arthur Fontaine
  • 176
  • 1
  • 11
1

You don't need to index your card value.

You need to adjust the first line of your loop as such:

for i in range(len(cards)):
    card = cards[i]
    print(f"{i+1} - {card}")

but this is not the most pythonic way. Instead what you can do is just call cards directly, and use enumerate if you need the index.

for index, card in enumerate(cards):
    print(f"{index+1} - {card}")
sshah98
  • 352
  • 4
  • 15
0

try changing the for loop to:

for i in range(len(cards)):