Reputation: 31
I am writing a console application which should close every time user type 'exit'. It works only when starting function is called once, otherwise I have to type 'exit' multiple times.
For example: I run the application, type "1", "recipe", "exit" and it works fine. When I type "1", [enter], "2", "exit" - i need to type "exit" one more time... or more (depending on function call times).
def start():
running = 'on'
while running == 'on':
recipes.show_recipes()
recipe_choice = input("...")
if recipe_choice == "exit":
running = 'off'
else:
try:
recipes.show_recipes(int(recipe_choice))
except IndexError:
print("...")
start()
except ValueError:
print("...")
start()
response = input("...")
if response == "recipe":
#opening recipe .pdf file
openrecipe(list(list(recipes.recipes.values())[int(recipe_choice)-1].values())[2], shell=True)
start()
elif response == "exit":
running = 'off'
else:
start()
start()
I suppose that solution is simple but I can't figure out why my application behave like that. I would like to close program any moment I type "exit" in console.
Upvotes: 0
Views: 277
Reputation: 77902
Your function is calling itself recursively, each time pushing a new frame to the call stack and starting a new loop. So if you end up piling say three recursive calls, the first "exit" will exit the last loop, the function execution finishes, the top frame is popped from the stack and the control goes back to the previous stack, so you're back to the second loop, etc (lather, rinse, repeat...)
Recursion is a useful tool when you have to deal with arbitrary nested data structures (trees etc) but it really doesn't belong here - it's both useless (a simple iteration is all you need) and harmful (it keeps on piling on frame after frame eating memory for no good reason and - as you discovered - makes flow control much harder than it has to be).
Upvotes: 1
Reputation: 101
You don't need to call start() over and over - once your program reaches the end of one of it's if clauses, it should start back at the head of the while loop. Otherwise, you're initiating new loops that you have to exit out of manually.
Upvotes: 4