Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Vincent C
Vincent C
1,376 Points

Variable is not defined error

Hello

The following script throws a "NameError: name 'guessed_number' is not defined " in line 21. But I don't understand why that would be the case.

Can anyone point me in the right direction?

Thanks. Vincent

import random

#generate a random number
random_number = random.randint(1, 10)
print(random_number)

#Instruction of the game
print("You have to guess a number and have 3 tries")

#Ask for a number
def ask():
    guessed_number = int(input("What's your guess? "))

#innitial counter of tries 
tries = 0

while tries < 3:
     #Ask for a numbers
    ask()
    #Compare random and guess number and show if low or high 
    if guessed_number == random_number:
        print("You won")
        break
    elif guessed_number > random_number:
        print("Too high")
        tries =+1
    else:
        print("Too low")
        tries =+1

1 Answer

Milo Gilad
Milo Gilad
1,663 Points

I believe the issue is that you're defining "guessed_number" in a function. When that happens, it stays inside that function and can only be used in that function. To fix this, you'll need to put at the very end of your function "return guessed_number". Then, replace "ask()" with "guessed_number = ask()". This will define "guessed_number" as what the ask() function defines it as.

Vincent C
Vincent C
1,376 Points

Thank you. I learnt something new here :)