I found an interesting piece of code in python:
def x(cond):
if cond:
pass
print('Still running!')
x(True)
I would expect this not to print anything, but it prints Still running!. What is happening here?
As per Python docs:
pass is a null operation — when it is executed, nothing happens.
Source - https://docs.python.org/3.5/reference/simple_stmts.html#pass
As such, pass does not do anything and all statements after pass will still be executed.
Another way of thinking about this is that pass is equivalent to any dummy statement:
def x(cond):
if cond:
"dummy statement"
print('Still running!')
pass does not mean "leave the function", it just means ... nothing. Think of it as a placeholder to say that you do not do anything there (for example if you do not have implemented something yet).
https://docs.python.org/3.5/tutorial/controlflow.html#pass-statements
If you want to exit the function, you just return or return None
By the way other useful statements are break to exit the latest loop and continue to exit the current iteration of the loop and directly go to the next one.
Pass does nothing. When the program gets there, it says "ok skip this!".
Pass can be used to define functions ahead of time. For example,
def function_somebody_is_going_to_write_later():
pass
def function_I_am_going_to_write_later():
pass
That way you could write a file with functions that other people might work on later and you can still execute the file for now.
Related
The title might be misleading, so here is a better explanation.
Consider the following code:
def minimum_working_environment(r):
trial=np.arange(0,6)[::-1]
for i in range(len(trial)):
if r>trial[i]:
return i
return len(trial)
We see that if r is smaller than the smallest element of trial, the if clause inside the loop is never executed. Therefore, the function never returns anything in the loop and returns something in the last line. If the if clause inside the loop is executed, return terminates the code, so the last line is never executed.
I want to implement something similar, but without return, i.e.,
def minimum_working_environment(self,r):
self.trial=np.arange(0,6)[::-1]
for i in range(len(self.trial)):
if r>trial[i]:
self.some_aspect=i
break
self.some_aspect=len(self.trial)
Here, break disrupts the loop but the function is not terminated.
The solutions I can think of are:
Replace break with return 0 and not check the return value of the function.
Use a flag variable.
Expand the self.trial array with a very small negative number, like -1e99.
First method looks good, I will probably implement it if I don't get any answer. The second one is very boring. The third one is not just boring but also might cause performance problems.
My questions are:
Is there a reserved word like return that would work in the way that I want, i.e., terminate the function?
If not, what is the best solution to this?
Thanks!
You can check that a for loop did not run into a break with else, which seems to be what you're after.
import numpy as np
def minimum_working_environment(r):
trial = np.arange(0, 6)[::-1]
for i in range(len(trial)):
if r > trial[i]:
return i
return len(trial)
def alternative(r):
trial = np.arange(0, 6)[::-1]
for i in range(len(trial)):
if r > trial[i]:
break
else:
i = len(trial)
return i
print(minimum_working_environment(3))
print(minimum_working_environment(-3))
print(alternative(3))
print(alternative(-3))
Result:
3
6
3
6
This works because the loop controlling variable i will still have the last value it had in the loop after the break and the else will only be executed if the break never executes.
However, if you just want to terminate a function, you should use return. The example I provided is mainly useful if you do indeed need to know if a loop completed fully (i.e. without breaking) or if it terminated early. It works for your example, which I assume was exactly that, just an example.
So I have 2 files, fish_life_simulator.py and menu.py. fish_life_simulator.py is the main file and executes other files like menu.py depending on what happens. So here is the code and how it should work:
import os
os.chdir(os.path.dirname(__file__))
result = exec(open(r'menu.py', encoding='utf-8').read())
print(result)
So at first when the code arrives to result = exec(open(r'menu.py', encoding='utf-8').read()) it executes menu.py and all is fine, but it could stop for several reasons:
The player exit the game
The player entered settings
The player pressed play
So what I decided to do, is when menu.py will stop running it will return a value, like 1, 2 or 3, so I tried several methods that have been included in here:
Best way to return a value from a python script
like using return or sys.exit("some value here"), but even though I did the part inside of menu.py, neither of them worked, as when I tried return, result from result = exec(open(r'menu.py', encoding='utf-8').read()) always was None for some reason and when I tried sys.exit(1) for example, result didn't get printed at all, so I was just wandering if it was something I was missing inside of fish_life_simulator.py, because the part with sending the value should be fine, but the part of receiving it is problematic.
Just define a function in menu.py:
def do_stuff_in_menu():
...
return result
and in fish_life_simulator.py you just call that function:
import menu
result = menu.do_stuff_in_menu()
print(result)
I agree with everyone who says exec() is not the best way to do this, however, since that's not your question, here's an answer for you.
The exec() function always returns None (see docs). If you need the return code, you could use os.system() or one of the various methods from the subprocess library. Unlike exec(), however, both of these alternatives would create a child process.
That said, I personally would not use any of those methods, but would instead modify menu.py to allow you to import it. It's much more natural and direct.
I would like to run exec() on 'return' in my function, so that my function returns and stops, here is my code:
def Function():#recieves time consuming function to do
#checks if main thread should be closed, if so returns:
return 'return "it worked"'
#otherwise returns 'Null' so main thread keeps going
def MainThread():
#Wants to do some function, so
exec(Function())
return "didnt work"
when I run MainThread(), it says:
SyntaxError: 'return' outside function
And I am not sure what is wrong there, I have simplified it and found that running exec('return') will also not work in a function.
Why I want to do this:
I have a thread that controls instruments, and before each command that it sends to the instruments I want it to check if it should abort, since controlling the instruments can be time consuming, and there are safety hazards. I don't want to copy-paste an if statement many times through my code, so thought of wrapping each command to an instrument with a check.
It seems quite messy, if there are other approaches I would love to hear.
My current solution is:
def Function(stuff):#recieves time consuming function to do
#does things to stuff
return
def check(thing,skip):
if skip==true:
return
else:
Function(thing)
return
def MainThread():
skip = False #will be true or false if need to skip
#Wants to do some function, so
check("the thing to do",skip)
If its necessary to abort the thread, it actually just skips through and does nothing at each function. At the end of the thread is aborts, but I didn't like simply keeping the thread there doing nothing and hoped for a better idea :)
exec() does not execute the code in the context of the function in which it is called. The "return "it worked"" does not become a part of Function(), it is executed on it's own.
Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21)
I have this:
def f():
try:
print "a"
return
except:
print "b"
else:
print "c"
finally:
print "d"
f()
This gives:
a
d
and not the expected
a
c
d
If I comment out the return, then I will get
a
c
d
How do I remember this behavior in python?
When in doubt, consult the docs:
The optional else clause is executed if and when control flows off the end of the try clause
Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.
Since you're returning from the body of the try block, the else will not be executed.
finally blocks always happen, save for catastrophic failure of the VM. This is part of the contract of finally.
You can remember this by remembering that this is what finally does. Don't be confused by other control structures like if/elif/else/while/for/ternary/whatever statements, because they do not have this contract. finally does.
The else block hooked up to a try block is not special in terms of exception mechanics - it's similar to just putting code in the body of the function after the try block. The only function is being able execute "normal" code between a try block and a finally block. This does mean however that if the function returns before getting to the else block it will never execute.
Take a look at Python documentation!
You would use this for exception handling, bookmark this page!
http://docs.python.org/2/tutorial/errors.html
You enter the try block.
You print "a".
You encounter the return statement and the function returns.
Since finally blocks always execute, though, everything in the finally block happens before the function actually ends its execution.
The else block is only entered if the try block has been completed and no exception occurred. Because you returned in the try block, it wasn't completed, even though no exception occurred nonetheless. It is as if you never had a try/else block at all, and you put all the code on the same level of indentation.
try/else exists more for the sake of code organization; unless a finally block is added, it is the same thing as using no else block at all. The following are functionally equivalent:
try:
print "foo"
except:
print "woops"
else:
print "bar"
try:
print "foo"
except:
print "woops"
print "bar"
However, you must use else if you are going to use finally. This has no meaning:
try:
print "foo"
except:
print "woops"
print "bar"
finally:
print "done"
What was the finally supposed to refer to in this case? Ergo you must use else if you are going to use finally unless you did not intend for anything to happen after the try block but before the finally.
When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).
This is actually from the documentation.
This question already has answers here:
return, return None, and no return at all?
(5 answers)
Closed 4 months ago.
Let's assume an iteration in which we call a function without a return value. The way I think my program should behave is explained in this pseudocode:
for element in some_list:
foo(element)
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return None
do much much more...
If I implement this in python, it bothers me, that the function returns a None. Is there a better way for "exiting a function, that has no return value, if a check fails in the body of the function"?
You could simply use
return
which does exactly the same as
return None
Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.
I would suggest:
def foo(element):
do something
if not check: return
do more (because check was succesful)
do much much more...
you can use the return statement without any parameter to exit a function
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return
do much much more...
or raise an exception if you want to be informed of the problem
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
raise Exception("cause of the problem")
do much much more...
return None or return can be used to exit out of a function or program, both does the same thing
quit() function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter.
import site
def func():
print("Hi")
quit()
print("Bye")
exit() function can be used, similar to quit() but the use is discouraged for making real world applications.
import site
def func():
print("Hi")
exit()
print("Bye")
sys.exit([arg]) function can be used and need to import sys module for that, this function can be used for real world applications unlike the other two functions.
import sys
height = 150
if height < 165: # in cm
# exits the program
sys.exit("Height less than 165")
else:
print("You ride the rollercoaster.")
os._exit(n) function can be used to exit from a process, and need to import os module for that.