Could someone please explain what happens in this python code? - python

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:
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.
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.

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.
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.

Related

Passing variables between functions in Python, then back to menu

Slowly progressing with my learning with Python and would love a little hand with some code I've tried to create.
I previously had this program running with Global Variables to get a proof of concept to learn about passing variables between functions. Fully worked fine. However, rather than running the function and returning to the menu, it will just stop where I return the value and not progress back to the main menu I created. It is at the point of "return AirportDetailsGlobal".
I'm sure its a simple one, and as said - still learning!
Really appreciate any help on this!
Full code is on pastebin for further reference - pastebin 89VqfwFV
print("\nEnter airport code for overseas")
osCode = input()
airports = airData
for line in airports:
if osCode in line:
print (osCode, "Found\n\n")
print("Airport Name:",line[1])
OverseaCodeGlobal = osCode
x = int(line[2])
AirDataGlobal = x #changed here
return AirportDetailsGlobal
break
else:
print('Incorrect Choice')
menu()
menu()
If you do a return then your code goes back to where it was called from. If it wasn't called from anywhere (ie. you just ran that script directly) then calling return is in most ways equivalent to calling sys.exit(), ie. the program terminates. It'll never hit your break, leave the loop, or hit your call to menu().
Also, your indentation as given there isn't right, the else is at the same level as the for, not the if. I don't think that's the problem but you might hit it next. ;-)

How do I run a function from an input before the code for the function has been read?

I am writing a game, similar to mastermind, and I want a choice bewteen an easy or hard version. I'm not sure how to do this as I need the question before the actual game starts but then there's an error because the function is being called to run before it has been assigned.
def difficulty():
difficulty = input("would you like to the easy or hard version?")
if difficulty == ("easy"):
easy()
elif difficulty == ("hard"):
hard()
difficulty()
This is the start then after is the function with the harder game code then the easier game code. I am trying to run the easy if they request easy and vice versa but the easy () and hard() don't run the code as it isn't assigned yet. I think this is because python reads the code from top to bottom and stops when it finds an error but not sure.
I have never used this before so I apologise if things are unclear or I have done some things wrong.
I am also relatively new to python.
If anybody could help me I would greatly apprectiate it.
Python is quite smart when it comes to identifying functions inside a module. For instance you could do this:
def x():
y()
def y():
print("Y")
x()
and it would execute correctly.
You are right about the execution of a code block that happens from top to bottom, as well as the definitions of those functions will also be constructed top to button, but executed afterwards.
I see some issues in your code.
you do difficulty = input("would you like to the easy or hard version?") but at the same time you have a function called def difficulty. There is a conflict there, try to rename that variable.
you don't need to do ("easy"), it's overkill, you can compare directly to "easy".

Can I continue an IF-ELSE statement through a function?

def you ():
gi=input("what up")
if gi in ["Nothing much", "nothing much", "nothing"]:
print("cool")
you()
elif gi in ["stuff"]:
print("sounds good")
I apparently cannot do this, however In a bigger program I am working on, I have a function that is used twice, however based of the user input, different results happen, so I tried to include my large function, and like the above program have an if else be continued throughout the function, because there are different options for user input, based on where the person is in the program.
I am just trying to figure out a good way to run a game, where the beginning is the same (function), however the game can progress in different ways, therefore a function won't work for all of it, so I just want to know if I can have an if else statement run through a function like in the small example above?
As James already said, no you cannot continue an if statement outside of a function. Referring to your question if functions are useful in a larger program: yes they are. You can use data generated in functions in your main program or other functions by returning your results. For instance:
def you ():
gi=input("what up")
return gi
result = you()
if result in ["Nothing much", "nothing much", "nothing"]:
print("cool")
elif result in ["stuff"]:
print("sounds good")

Play again feature not working in program

I've written a beginner program to play a game. The main structure of the program nests various functions within an outer, parent function. I had a question about calling fparent() from within fnested().
NOTE: Sadly I cannot share the original code as this is for university and due to academic integrity policies I cannot make the code public.
The idea behind the implementation is that if a user wants to repeat the program, they should input a valid indicator, YES. This happens within a nested function. The program seeks to recognise this input and thus call fparent() once more, re-starting the program.
This is currently not working.
I wanted to know if there is a way to code this feature
Links to existing answers are most welcome as I couldn't find anything that helped me directly with this.
If you tried to call the parent function directly from nested it will give you "stack overflow" maximum depth reached.
As you stated the problem :
they should input a valid indicator, YES. This happens within a
nested function. The program seeks to recognise this input and thus
call fparent() once more, re-starting the program.
You can try something like this:
def f0():
def f1():
print("do some stuff in function f1")
def f2():
print("do some stuff in function f2")
def f3():
print("do some stuff with function f3")
user_input=str(input("Do you want to repeat the program Yes or No >> "))
map_userinput={"Yes":f0,"Level2":f2,"Level3":f3}
if user_input=="Yes":
print("ok calling the parent function from nested function")
map_userinput[user_input]()
elif user_input=="Level2":
map_userinput[user_input]()
else:
print("continue with this nested function")
f0()

Runtime Error: Maximum Recursion Depth Exceeded when Using exit(0) in python

I'm going through "Learn Python the Hard Way" by Zed Shaw.
I'm currently on lesson 36: http://learnpythonthehardway.org/book/ex36.html
My issue:
I'm trying to create my own game based on what Zed did in lesson 35: http://learnpythonthehardway.org/book/ex35.html
In his game he creates the following function to terminate the game:
def dead(why):
print why, "Good job!"
exit(0)
That's used in if/else statements such as this:
choice = raw_input("> ")
if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
When I run his program it exits when calling the dead function.
However, when I try and use this same construct in my own code I get the following error:
RunTime Error: Maximum Recursion Depth Exceeded
after lines of code spitting out the spot in my program where the exit(0) function is called.
Here's an example of how I have used it in my program:
def exit(message):
print message, "Your adventure is over."
exit(0)
With if/else statements like this:
answer = raw_input("> ")
if "stay" in answer:
exit("Adventure and excitement are only available to those who participate.")
elif "don't" in answer:
exit("Great things were never achieved by cowards. Please rethink your choice.")
elif "wait" in answer:
exit("Great things were never achieved by cowards. Please rethink your choice.")
elif "outside" in answer:
exit("Adventure and excitement are only available to those who participate.")
elif "enter" in answer:
lobby()
elif "go" in answer:
lobby()
elif "through" in answer:
lobby()
elif "inside" in answer:
lobby()
else:
exit("Well, you're no fun!")
It's not clear to me why it works in Zed's program but doesn't in my own. (And yes, I know that's probably an egregious use of elif's but my programming chops prohibit me from doing much else right now).
At first I thought it was due to how I was using while loops in my program but I've deleted all those and I'm having the same issues.
Thank you.
It's pretty simple. You named your function exit(), and your function tries to call a function named exit(). Thus your function calls itself, then calls itself again, and again, and again...
When a function calls itself, this is called a recursive call. If your function calls itself over and over too many times, eventually a limit is reached and Python stops your program. Python raises an exception, telling you that the "maximum recursion depth" was reached.
Here's a simple fix:
import sys
def dead(why):
print why, "Good job!"
sys.exit(0)
Now your program is explicitly asking for a particular exit() function, the one inside sys. Instead of calling itself recursively forever, it calls sys.exit() once and your program will stop.
Another solution is simply to rename your function to something other than exit(). Zed called his dead() which is why his example works.

Categories