for example i have def Hello():
and here is the code
def Hello():
F = 'Y'
if F == 'Y':
#here i want get out of the Hello() to Hey()! by how!
To exit the 'Hello' function:
def Hello():
F = 'Y'
if F == 'Y':
return
You can use 'return' to exit a function before the end (though there is a school of thought that frowns on this, as it makes it slightly harder to form a solid picture of the execution flow).
This will go on to the 'Hey' function if you called it with e.g.:
Hello()
Hey()
Or, to 'jump' to the 'Hey' function, use:
def Hello():
F = 'Y'
if F == 'Y':
Hey()
...but this means the call stack will still contain the data for the 'Hello' function - so when you return from the 'Hey' function, you will be returning to within the 'Hello' function, and then out of that.
Related
def user(choose):
if (choose == "1"):
play = game()
elif (choose == "2"):
return stats(play)
else:
return quit()
I want to take the value from function game() and use it in stats(), but I get an error saying that play is not defined. How do I declare game() and use it in another function?
You could "postpone" execution of func1:
def func1():
return 'abc'
def something_else(callable):
callable()
def main():
hello = None
def f():
"""set result of func1 to variable hello"""
nonlocal hello
hello = func1()
# over here func1 is not executed yet, hello have not got its value
# you could pass function f to some other code and when it is executed,
# it would set result for hello
print(str(hello)) # would print "None"
call_something_else(f)
print(str(hello)) # would print "abc"
main()
After question has changed...
Right now, your local variable play is out of scope for stats.
Also, looks like you expect that function would be called twice.
You need to save play in global content
play = None # let's set it to some default value
def user(choose):
global play # let python know, that it is not local variable
if choose == "1": # no need for extra brackets
play = game()
if choose == "2" and play: # double check that play is set
return stats(play)
return quit()
Why is it that when this code is executed, I would get 'hi'?
Thanks!
def b():
print("hi")
def c():
return True
if b() == 'hi':
print("Done")
You are confusing printing to the console with returning a value. Your function implicitly returns None if you do not return anything from it so it is never equal to 'hi'. Your b() does print - and not return its 'hi'
def b():
print("hi") # maybe uncomment it if you do not want to print it here
return "hi" # fix like this (which makes not much sense but well :o)
def c():
return True
if b() == 'hi':
print("Done")
You can test it like this:
def test():
pass
print(test())
Outputs:
None
Further readings:
about the return statement
about defining functions (read the paragraph below the second fib-CodeBlock example - it tells you about None)
One even more important thing to read: How to debug small programs (#1) - it gives you tips on how to fix code yourself and find errors by debugging.
Essentially what you're doing is saying if b(), which runs the b() function and prints "hi" is equal to "hi", print "done", but since your function prints "hi", rather than returning "hi", it will never equal true.
Try this:
def b():
return "hi"
def c():
return True
if b() == 'hi':
print("Done")
I declared 3 functions earlier, this is just a goofy text based cookie clicker-esque game.
dostuff={"" : turn() , "help" : helpf() , "invest" : invest() }
while done != True:<br>
do = input("What do you want to do? ")
do = do.lower()
if do == "" or do == "help" or do == "invest":
dostuff[do]
elif do == "quit":
done = True
So when I use dostuff["turn"] it does nothing (the function is supposed to print some things). I have the same problem with the other options.
Your parentheses must be omitted in the dict, and then put at the end of the dict call. You define a function, which becomes a python object. You reference the object with the dict, and then you call the function with the object reference followed by parentheses:
def one():
print("one")
def two():
print("two")
do_stuff = {
"one": one,
"two": two
}
do_stuff["one"]()
prints:
"one"
You can take this concept of executing calls with string inputs a lot farther by familiarizing yourself with the builtin functions of python.
https://docs.python.org/2/library/functions.html
For example, you can create a class and call its methods or properties using text based input with the getattr method:
class do_stuff():
def __init__(self):
pass
def one(self):
print("one")
def two(self):
print("two")
doer = do_stuff()
inp = "one"
getattr(doer, inp)()
prints->
"one"
I am creating a simple debugger using python and trying to create breakpoint when an expression holds.i am using the eval function to evaluate that expression.but it does not work.
def traceit(frame, event, trace_arg):
if event == 'line':
if(eval('x == 5')):
print 'stop here'
def fn():
#the variable x is defined and used here
sys.settrace(traceit)
fn()
sys.settrace(None)
You need to pass a dictionary as an argument for locals and globals to the eval function (so that it knows what x is! -- Otherwise it's just guessing and it picks up the local context which isn't the context of the function fn)
You can get the locals and globals values from the stack frame object in the f_locals and f_globals attributes respectively.
I think you probably want something like:
eval('x == 5',frame.f_locals,frame.f_globals)
As a side note, you probably don't actually need eval for this (static) case:
if frame.f_locals.get('x') == 5:
print "stop here"
Here's some "working" code (i.e. it prints "stop here" in the right spot):
import sys
def traceit(frame, event, trace_arg):
if event == 'line':
if 'x' in frame.f_locals or 'x' in frame.f_globals:
if(eval('x == 5',frame.f_locals,frame.f_globals)):
print 'stop here'
return traceit
sentinel = object()
def trace_no_eval(frame, event, trace_arg):
if event == 'line':
value = frame.f_locals.get('x',frame.f_globals.get('x',sentinel))
if value is not sentinel and value == 5:
print 'stop here'
return traceit
def fn():
for x in range(10):
print x
sys.settrace(traceit)
fn()
sys.settrace(trace_no_eval)
fn()
sys.settrace(None)
As you said that this is an assignment, please do not blindly copy this. Take the time to understand it and really understand what is going on.
Assume I have the following ;
def test():
while 1:
a = b
time.sleep(60)
c = b
if(c==a):
do something
then quit the function
What is the proper way to quit from a function having this structure ?
You could just use a return statement.
That would be the most direct way, by just placing the return where you want to quit ("then quit the function").
if(c==a):
do something
return
You could also use this to return any results you have to the calling code.
Eg., return some_results
Python doc for return
Use the return statement: eg
def test():
while 1:
a = b
time.sleep(60)
c = b
if c == a:
print a
return
break would also work, by leaving the while loop.
Just use the return statement to exit the function call.
def blah():
return # Returns None if nothing passed back with it
def blah():
return some_value, some_value2 # Return some values with it if you want.