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.
Related
I have a function inside a class, that calls other functions and does some stuff until it obtains two variables, A and B:
Class NumberLogic:
def compare():
#do stuff_
A=#do stuff__
B=#do stuff___
if A<B:
return 1
else:
return 2
I would like to test this function compare() but give values directly from A and B so only the if condition is tested, I am not sure if this is possible and the rest of the code can be mocked so when I call someting like
assert 1 == NumberLogic.compare()
You could rewrite your code like this:
Class NumberLogic:
def compare(self):
A = self._get_A()
B = self._get_B()
return self._compare(A, B)
def _get_A(self):
# do stuff
return A
def _get_B(self):
# do stuff
return B
def _compare(self, A, B):
if A<B:
return 1
else:
return 2
This way you can write your code to check only the _compare
Note: Starting a function with an underscore signifies it's an internal method only used by the function itself.
You could also write:
def _compare(self, A, B):
if A<B:
return 1
return 2
Which is the same thing
Instructions:
First, def a function called distance_from_zero, with one argument (choose any >argument name you like).
If the type of the argument is either int or float, the function should return >the absolute value of the function input.
Otherwise, the function should return "Nope"
I've done the first task and I thought that i completed the task, however
"Your function seems to fail on input True when it returned 'None' instead of 'Nope'"
Here is my code:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
return abs(argument)
print(argument)
else:
print("Nope")
From what ive seen in other modules codecademy tests this with my arguement being "1", such that the if statement goes through, will return the absolute value of (argument) and then i would pass the module. (i added print(argument) for testing purposes, the console outputs nothing.)
Am i mis understanding how returning works? Why is this not working?
I appreciate all responses! :)
EDIT: It prints "None", not "Nope" in the console. Forgot to mention this.
In Python, if return isn't explicit, it becomes None. Try this:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
print(abs(argument))
else:
print("Nope")
> f = distance_from_zero(-4234)
4234
> f
None
As you can see the value of f is None, this is because print is outputting to the console and not actively returning content. Instead, try using the return statement:
def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
return abs(argument)
else:
return "Nope"
> distance_from_zero(123)
123
# here, because you're not assigning the value returned to a variable, it's just output.
> f = distance_from_zero(-4234)
> f
4234
> f = distance_from_zero('cat')
> f
'Nope'
It's also important to know that the reason this:
return abs(argument)
print(argument)
printed to the console is not because of the print call. Anything after return in a block is not executed. The reason you see the output printed to the screen is because in the interpreter Python outputs all function return values not collected into variables.
def distance_from_zero(num):
if type(num) == int or type(num) == float:
return abs(num)
else:
return "Nope"
I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function compute_gcd computes the GCD and returns it which gets printed in the main function. However, the output is none when I return it to the main function and it is 12 when I print it in the compute_gcd function itself.
Where am I going wrong while returning the GCD?
def compute_gcd(a,b):
if(b==0):
return a # Prints 12 if I replace with print a
else:
compute_gcd(b,a%b)
def main():
a=24
b=12
print compute_gcd(a,b) # Prints none
main()
You forgot to put a return in the else branch. This works:
def compute_gcd(a,b):
if b == 0:
return a
else:
return compute_gcd(b,a%b)
def main():
a=24
b=12
print compute_gcd(a,b) # Prints 12
main()
try this ... you have to do a return inside the else statement
def compute_gcd(a,b):
if(b==0):
return a
else:
return compute_gcd(b,a%b)
def main():
a = 24
b = 12
print(compute_gcd(a,b))
main()
Your else condition has no return hence output is none. If you change that to
else:
return compute_gcd(b,a%b)
You'll get 12.
I have a sub program that uses a def option, so if i ever want to repeat the program. Eg:
def op1():
print ("Something Something")
So I just write in the program:
op1()
which makes the program run.
Now I have a lot of subprograms each one with a different def so I can run them by easily.
eg:
def op1():
def op2():
def op3():
So I wanted to know how can I use this in if-else statement.
eg:
option = input ("Enter either A, B or C here: ")
if option == A:
def op1():
else:
def op2():
or even
if option == A:
def op1():
elif:
def op2():
elif:
def op3():
Something like that, but it doesn't work. Can anyone help, Please?
Also I'm using the newer version of python if that helps 3.5.0.
You do not need to define functions conditionally.
def op1():
print('1')
def op2():
print('2')
def op3():
print('3')
if option == 'A':
op1()
elif option == 'B'::
op2()
else:
op3()
You need to define your functions first but if you have multiple choices you can store references to functions in a dict then call based on what the user enters, using dict.get with a default function will act like your if/elif else logic:
def op1():
return '1'
def op2():
return '2'
def op3():
return "3"
option_fs = {"A": op1, "B": op2}
option = input("Enter either A, B or C here: ").upper()
print(option_fs.get(option, op3)())
I try:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
exec(s)
return s
print test("TEST12344","[:2]")
its return 'TEST12344'[:2]
How to return value from exec in function
Think of running the following code.
code = """
def func():
print("std out")
return "expr out"
func()
"""
On Python Console
If you run func() on the python console, the output would be something like:
>>> def func():
... print("std out")
... return "expr out"
...
>>> func()
std out
'expr out'
With exec
>>> exec(code)
std out
>>> print(exec(code))
std out
None
As you can see, the return is None.
With eval
>>> eval(code)
will produce Error.
So I Made My exec_with_return()
import ast
import copy
def convertExpr2Expression(Expr):
Expr.lineno = 0
Expr.col_offset = 0
result = ast.Expression(Expr.value, lineno=0, col_offset = 0)
return result
def exec_with_return(code):
code_ast = ast.parse(code)
init_ast = copy.deepcopy(code_ast)
init_ast.body = code_ast.body[:-1]
last_ast = copy.deepcopy(code_ast)
last_ast.body = code_ast.body[-1:]
exec(compile(init_ast, "<ast>", "exec"), globals())
if type(last_ast.body[0]) == ast.Expr:
return eval(compile(convertExpr2Expression(last_ast.body[0]), "<ast>", "eval"),globals())
else:
exec(compile(last_ast, "<ast>", "exec"),globals())
exec_with_return(code)
exec() doesn't just evaluate expressions, it executes code. You would have to save a reference within the exec() call.
def test(w, sli):
exec('s = "{}"{}'.format(w, sli))
return s
If you just want to evaluate an expression, use eval(), and save a reference to the returned value:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
s = eval(s)
return s
However, I would recommend avoiding exec() and eval() in any real code whenever possible. If you use it, make sure you have a very good reason to do so.
My findings in Python 3.8 in 2020
in Eval Logic :
a="1+99"
a=eval(a)
print(a) # output: 100
in exec logic
exec ("a=33+110")
print(a) #output 143