Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 :)