Welcome to the Treehouse Community
Looking to learn something new?
Vincent C1,376 Points
Variable is not defined error
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?
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
Milo Gilad1,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.