2

I am quite new in programming scene. I was having a hard time grasping the very nature of this code.

import time
from random import randint

replies =["Yes","No","Possibly", "Ask again later", "IDK"]

def question():
    print "What is your question?"
    question = raw_input()
    print "Thinking"
    time.sleep(3)
    print replies[randint(0,4)]
    end()

def end():
    print "Thanks for playing! Do you want to try again?"
    user_reply = raw_input()
    if user_reply == "yes":
        question()


print "Welcome to the magic 8-ball"
question()

My questions are:

  1. As you can see the end() function was called inside the question() function. And suppose that i keep playing the game. What happens to previous caller especially the very first question()? Is it still open? or is it closed once it called end() function.
  2. Would that build up memories as long as i keep playing the game? I know that the memories are cleared up once the functions end, but in this code it just keeps calling a function. The only time it ends is if you close the program.

Thank you.

Dimasalang
  • 23
  • 3
  • It's kind of recursion, but as you're not programming in Assembly or C you should not worry about that, python itself will handle the memory and overhead in proper way, unless you are doing that in loop for huge amount of times – Serjik Nov 06 '16 at 11:24

1 Answers1

2
  1. What happens to previous caller especially the very first question()? Is it still open?

The question() function is still "open", or at least still running, with all of its variables and other resources being used.

This is called "recursion" and is very worth of your study. Function question() is called, which calls end(), and if the player chooses to continue, this again calls question() which calls end(), etc. You get a stack of functions, alternating between question() and end(), all of which still exist and take resources. If the game continues too long, all the available resources will be consumed and the programs ends with a stack overflow error--appropriate for this site!

Each of those calls happens at the end of the calling routine, and this situation is called "tail recursion." Some compilers for a computer language can recognize this and replace the recursion with a loop, so the calling routine is indeed closed down before the new routine begins. I do not believe the standard Python interpreter does this, so the routines will build up on the computer stack.

  1. Would that build up memories as long as i keep playing the game? Yes, that would build up items in computer memory--at least if the computer environment does not recognize the tail recursion.
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50