Welcome to the Treehouse Community
Looking to learn something new?
Grigorij Schleifer10,363 Points
Number guess game "reversed"
Hey treehouse friends,
I nee help understanding the variable concept inside python.
I have created a number game where the computer guesses the number of the user.
But it doesnt work ;((((
# -*- coding: utf-8 -*- import random # create a list to store the computer guesses list =  print("Input a number between 0 and 10") # user input method def input_number(): while True: try: num_to_guess = int(raw_input("> ")) break except ValueError: print("Something went wrong") def game(): # let the computer gueess until the length of the list is 10 while len(list) < 10: # create the random number pc_num = random.randint(0, 10) list.append(pc_num) if pc_num == num_to_guess: print("PC got it") break #call the method to get the number from the user input_number() # start the game game() #print the list print(list)
The error is:
Input a number between 0 and 10 > 6 Traceback (most recent call last): File "reverse_guess_game.py", line 34, in <module> game() File "reverse_guess_game.py", line 26, in game if pc_num == num_to_guess: NameError: global name 'num_to_guess' is not defined
What is the meaning of the global name not defined?
Every help is highly appreciated.
Steven Parker215,939 Points
Your issue seems to be because num_to_guess is defined within the input_number() function, but the game() function is trying to access it.
num_to_guess = 0 up where you define list. That will make it global, and accessible by both functions.
Actually, the first error I got when trying this was "NameError: name 'raw_input' is not defined". Is there a missing import? But I changed it to plain input.