[Beginner]Program wont work quite how I expected.

Also, calling the function from within the function like that isn't a proper way to loop. This is what you have:

def game():
    x = random.random()
    game()

game()

Each time you call a function, you can look at it as: python creates a new instance of that function before entering it. All of the variables and whatnot inside that function area created, new, time you enter the function.

So, in the above, when you go into the game function the first time, python creates a new instance of it, creates a new x variable, and stores a random value into that x variable. Now, before that first function can exit, you call it again. Python then creates a new instance of the game function, and a new x. That first instance still has to exist because it never exited.

def a():
    msg = "poop"   # store "poop" in msg
    b()                  # call b. all the variables and state here in a have to be maintained because we'll come back from b to continue below.
    print msg         # print msg

def b():
    print "monkey"

a()
> money poop

So, since you call game within game, forever, the state of each call to game has to be stored. This is called a "call stack". Python keeps track of all this game() #1 -> game() #2 -> game() #3, etc. Eventually (I think python can do 1024?), you'll run out of memory and get an error.

So, the solution is to never do this, unless you know that the recursive function calls will eventually end.

Use a regular loop. I would use a while loop. And, you can throw in error checking for the int conversion.

while True:  # always loop
    try:
        guess = int(guess)
    except ValueError:
        print "That's not a number fool."
        continue # skip all the code below, and go back up to the top of the while loop
    if guess == number:
        #blah
/r/learnpython Thread