[Python] Don't understand the error

Solved

First a bit of my code:

def new_game():
num = 100
secret_number = random.randint(0,100)
remaining_turns = math.ceil(math.log(num+1,2))

def input(guess):
global remaining_turns, secret_number
remaining_turns = remaining_turns - 1

NameError: name 'remaining_turns' is not defined

What am I doing wrong here? I thought I defined it on line 4, yet it says its undefined on line 8. Am I misunderstanding how to use global and local variables?

Posted Mar 5, 2015, 3:48 AM UTC

12
Updatebjarni•

Am I misunderstanding how to use global and local variables?

Yes. Your new_game() function creates a local variable, and your input() function tries to access a global variable which new_game() didn't create. It isn't enough to say global in one function in the program, that doesn't make the same name global in all other functions.

1
strokeyOP•

Oh I see, thanks, fixed it!

1