Skip to content
Advertisement

NameError: name ‘i’ is not defined – Why does this happen?

I am making a rather simple wordle clone for my class. It functions exactly the same as wordle, just in a CLI. However, I am getting a weird error when testing.

When executed, python returns

Traceback (most recent call last):
File "<string>", line 46, in <module>
File "<string>", line 19, in input_guess
NameError: name 'i' is not defined

The code is

def input_guess():
    #gets input
    while True:
        guess = (str(input(f"Attempt {i + 1} >>> " ))).lower()
        if len(guess) != 5 or guess == int:
            print("Invalid input")
            continue
        else:
            return guess.lower()

def split(word):
    #splits word
    return list(word)

while attempts < 6:
   # wordle
    guess = split(input_guess())
    for i in guess:
        if guess[i] == word[i]: #green
            response[i] = guess[i]
        if guess[i] in word and guess[i] != word[i]: # yellow
            response[i] = "-"
        if guess[i] not in word: #miss
            response[i] = "_"

Why am I getting this error? What am I doing wrong? I can’t seem to wrap my head around it.

Cheers

Advertisement

Answer

Your file is being read logically, top to bottom. You don’t define ‘i’ until your ‘for’ loop inside your ‘while’. If you want ‘i’ to be accessible by input_guess, you need to either define it in a line before the function is defined or pass it in as a parameter into the function call, like guess = split(input_guess(i))

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement