Python Forum

Full Version: Getting Name Error: Name not defined
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am a new user, just at very beginning. I am trying to write a simple function but I get the name error saying that I have not defined a variable. This variable is defined in my if statement, where it should return its value. Can anyone please help me to understand what I am doing wrong. Thank you.

# A program to get three guesses from user.
# Defining guess check function.
def check_guess(letter, guess):
    if guess.isalpha():
        guess_check = letter == guess.lower()
        return guess_check
    else:
        print("Invalid input. Your guess is False.")


# creating a while loop with attempt counter
attempt = 0
print("Let\'s start the guessing game. You get three tires. \n")
while attempt < 3:
    letter_input = "j"
    attempt += 1
    print("This is your attempt #",str(attempt) + ".")
    user_guess = input("Enter an alphabet: ")
    check_guess(letter_input,user_guess)
    if guess_check == True:
        print("Your guess is correct! You won in your try #", str(attempt) + "!")
        break
    else:
        pass
Error:
"D:\Web Sync Folders\Dropbox\Study\Data Science\python_learning\venv\Scripts\python.exe" C:/Users/home/.PyCharmCE2019.1/config/scratches/scratch.py Let's start the guessing game. You get three tires. This is your attempt # 1. Enter an alphabet: 5 Traceback (most recent call last): Invalid input. Your guess is False. File "C:/Users/home/.PyCharmCE2019.1/config/scratches/scratch.py", line 19, in <module> if guess_check == True: NameError: name 'guess_check' is not defined Process finished with exit code 1
Variables defined in a function are only visible within that function. You need to return guess_check from the function, and then assign it where you call check_guess. That will bring the value out of the function. See the function tutorial link in my signature below for more details.
Thanks a lot Craig. It worked and helped me understand a big mistake. Thanks again.