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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Vincent C](https://uploads.teamtreehouse.com/production/profile-photos/7174322/micro_dragon.jpg)
Vincent C
1,376 PointsVariable 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](https://uploads.teamtreehouse.com/production/profile-photos/8058152/micro_croppedsteamworkssouthflorda.jpg)
Milo Gilad
1,663 PointsI 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
1,376 PointsVincent C
1,376 PointsThank you. I learnt something new here :)