hoodoo
hoodoo

Reputation: 33

python does not exit program properly

In my program I want to interact with user and ask him to press specific letters to do some things (I think that logic of this game is not relevant for my question). When I start game and as first letter I press 'q' program exit immediately, but when I play for a while (use few times 'g' and 'r') I have to press few times 'q' too before I could exit program (Every time I'm getting the same prompt as on the beginnig of the game "Enter g to start ... ") I'm using Canopy and Python 2.7.

t_h = '' 
def pg(wl):

    global t_h
    result = raw_input("Enter g to start new game, r to replay last game, or q to end game: ")
    possible_choices = ["g", "r", "q"]
    if result in possible_choices:
        if result == 'g':
            t_h = dh(n)
            ph(t_h, wl, n)
        if result == 'r':
            if t_h == '':
                print 'You have not played a game yet. Please play a new game first!'
            else:
                ph(t_h, wl, n)
        if result == 'q':
            return None
    else:
        print "Invalid letter." 
    return pg(wl)

Upvotes: 1

Views: 147

Answers (2)

h7r
h7r

Reputation: 5074

The function pg calls itself recursively on any non possible_choice case (since only q returns directly) -- that is, on the return pg(wl) line.

The situation you describe implies that either one of, or both ph and dh are calling pg again. This means that for every non q input you will have a prompt for a new question on the stack from ph (or ph and dh) and one from the recursive call to pg. This will cause the exact behaviour you describe, where one q wont suffice to exit. With the code you posted -- that is, without dh and ph -- it is not possible to know precisely, but this is the logical conclusion.

If you want the possibility to exit immediately you would have to use a simple infinite loop with break in case of q instead of recursion. Another possibility is following @PauloScardine's idea of using exit(), if what you want is really to exit the whole process. Again, with the piece of code you posted, it is not possible to know whether this is possible (pg being called directly from a main function).

Upvotes: 1

Spice
Spice

Reputation: 352

It's difficult to tell without seeing more of your code (specifically code for dh and ph), but I'd guess that pg is being called from one of those functions, or some other function in your code.

Upvotes: 1

Related Questions