How do I use multiple variable from one function into another? [duplicate] - python

This question already has answers here:
Alternatives for returning multiple values from a Python function [closed]
(14 answers)
Closed 9 months ago.
When I try to call a, b in function add, I get a is not defined even though I am returning the values. How do I make it return both a and b?
def numbers():
a= input ("a:")
a = int(a)
b= input ("b:")
b = int(b)
return a
return b
def add():
numbers()
print (a)
print (b)
add()

A return statement almost always causes a function to immediately terminate, and no other statement in the function will run. So once you return a, you'll never get to return b. You need to return both of them at the same time.
Additionally, returning a value from a function will not automatically put those names into the scope that called the function. You need to manually assign the values to something.
def numbers():
a= input ("a:")
a = int(a)
b= input ("b:")
b = int(b)
return a,b
def add():
a,b = numbers()
print (a)
print (b)
add()

I think so:
def numbers():
a= input ("a:")
a = int(a)
b= input ("b:")
b = int(b)
return a, b
def add(a, b):
print (a)
print (b)
return a, b
def main():
another_a, another_b = numbers()
another_a, another_b = add(another_a, another_b)
main()

Related

How is good the practis to compare arguments of function with it's names in Python?

I've made example functions, I know that i will use meta_function only with arguments sum and mult
def sum(a, b):
return a + b
def mult(a, b):
return a*b
def meta_function(function):
if function == sum:
c = 1
print('SUM')
elif function == mult:
c = 2
print("MULT")
print(c)
meta_function(sum)
meta_function(mult)
Output:
SUM
1
MULT
2
PyCharm informing me that Local variable might be referenced before assignment. I know, if some other arguments will be taken except sum and mult, this will lead to error. What is the best practice to handle this sophisticated issue? Try - except? Am I use wright way to take another functions in meta_function?
Pycharm warns you because if the function isn't sum or mult, your code will crash.
You need to define c at the top, just in case, or add an else statement.
# I changed the name of sum_ in order to avoid shadowing with
# the python built-in function sum()
def sum_(a, b):
return a + b
def mult(a, b):
return a * b
def meta_function(function):
c = 0 # if function isn't sum or mult, at least c exist
# here, "is" is better then "=="
if function is sum_:
c = 1
print('SUM')
# here, "is" is better then "=="
elif function is mult:
c = 2
print("MULT")
# Or you can do the else, but since you don't do anything in it,
# the best solution is to define a base state of c
# else:
# c = 0
print(c)
meta_function(sum_)
meta_function(mult)
Here is a better solution in my opinion, in order to prevent changing the core of meta_function() if you want to add more functions:
def sum_(a, b):
return a + b
def mult(a, b):
return a * b
function_switch = {
sum_: ('SUM', 1),
mult: ('MULT', 2),
}
def meta_function(function):
function_res = function_switch.get(function)
if function_res is None:
print(0)
return
print(function_res[0])
print(function_res[1])
meta_function(sum_)
meta_function(mult)
In Python 3.9, you can do:
def meta_function(function):
if (function_res := function_switch.get(function)) is None:
print(0)
return
print(function_res[0])
print(function_res[1])
Warning is shown because if both cases are not happened, then variable c will be not defined and print fill fail. The variable must be defined in the current scope.
It is better to make a generic function, executes the function and returns desired values. I've refactored your function as taking callable function and parameters for given function. Executes given callable and return some string that is built with return results.
def sum(a, b):
return a + b
def mult(a, b):
return a*b
def meta_function(func, *args):
# initialize default variables
c: int = None
return_str: str = None
# try execute given callable `func`
try:
# execute
c = func(*args)
# build some result string and assign
return_str = f"Function:{func.__name__}, Args: {args}, Result: {c}"
except Exception as exp:
# build result string for failed functions
return_str = f"Error calling given function `{func.__name__}` with params: {params}"
return return_str
def incompatible_func(x, y, z): # takes three parameters, will fail
return x + y * z
params = (1,2)
rslt = meta_function(sum, *params)
print(rslt)
rslt = meta_function(mult, *params)
print(rslt)
rslt = meta_function(incompatible_func, *params)
print(rslt)
And the output is:
Function:sum, Args: (1, 2), Result: 3
Function:mult, Args: (1, 2), Result: 2
Error calling given function `incompatible_func` with params: (1, 2)

Confusion as to function parameters [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 years ago.
I am trying to make a simple function that accepts 2 parameters, and adds them together using "+".
def do_plus (a,b):
a=3
b=7
result = a + b
print (result)
However, I get no value returned, the function is executed but no output is shown.
You're missing the indentation.
a=3
b=7
def do_plus (a,b):
result =a+b
print (result)
# and you have to call the function:
do_plus(a,b)
You probably want to separate logic from input/output, as so:
def do_plus(a, b):
result = a + b
return result
res = do_plus(3, 7)
print(res)
try this:
def do_plus (a,b):
print=a+b
do_plus(3, 7)
you can call your function "do_plus" passing parameters and print wath the function return
Attention to the "spaces" before result is important in python the identation of script
It's hard to tell from your code because the indentation is off, but a simple addition function can be something like:
def addition(a, b):
return a + b
You are accepting parameters a and b, but then assigning them values 7 and 3, so that no matter what, it will return 10.

Python BST code returning None instead of array? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
The following code returns None on some values (eg 306, 136), on some values (42, 84), it returns the answer correctly. The print a and return a should yield the same result, but it does not:
def gcdIter (a,b):
c = min (a,b)
d = max (a,b)
a = c
b = d
if (b%a) == 0:
print a
return a
gcdIter (a,b%a)
print gcdIter (a,b)
You are ignoring the return value for the recursive call:
gcdIter (a,b%a)
Recursive calls are no different from calls to other functions; you'd still need to do something with the result of that call if that is what you tried to produce. You need to pass on that return value with return
return gcdIter (a,b%a)
Note that you can assign to multiple targets when assigning:
def gcdIter(a, b):
a, b = min(a, b), max(a, b)
if b % a == 0:
return a
return gcdIter(a, b % a)
You really don't need to care about the bigger and smaller values here. A more compact version would be:
def gcd_iter(a, b):
return gcd_iter(b, a % b) if b else abs(a)

How to tell if a function will be returning a value to a variable?

So to give as an example, imagine a function that computes a value and will either return the value to the variable or print it if it will not be stored into a variable such as:
def add(a, b):
c = a+b
if called: return c ## Put the value into "answer" below
else: print "Your answer is: ", str(c) ## just print it
answer = add(10, 15)
print answer
## Should print 25
add(10, 20)
## Should print """Your answer is 30"""
I want to use this in various functions such as a UI or a generator but can't find a way to implement a Boolean statement to determine this.
I Googled this, and the only thing i found close was determining if the function was called or recursed(?). I just want the function to know if it should return the value to the variable or simply print it. Any ideas?
A python function has no information on whether it's return value is being assigned or ignored. So, what you want is not possible.
If you are willing to make some design changes, you could add a parameter:
def add(a, b, print_it):
c = a+b
if print_it: print "Your answer is: ", str(c) ## just print it
else: return c ## Put the value into "answer" below
answer = add(10, 15)
print answer
## Will print 25
add(10, 20, true)
## Will print """Your answer is 30"""
Or you could define a wrapper function specifically for printing the result:
def add(a, b):
c = a+b
return c
def print_add(a, b):
print "Your answer is: ", str(add(a, b)) ## print add's return value
answer = add(10, 15)
print answer
## Will print 25
print_add(10, 20)
## Will print """Your answer is 30"""
You could make the second solution more generic by passing the base function to the wrapper function:
def add(a, b):
c = a+b
return c
def sub(a, b):
c = a-b
return c
def print_result(fn, a, b):
print "Your answer is: ", str(fn(a, b)) ## print function's return value
answer = add(10, 15)
print answer
## Will print 25
print_result(add, 10, 20)
## Will print """Your answer is 30"""
print_result(sub, 10, 20)
## Will print """Your answer is -10"""
etc, etc.

Why Python recursive function returns None [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
The following code returns None on some values (eg 306, 136), on some values (42, 84), it returns the answer correctly. The print a and return a should yield the same result, but it does not:
def gcdIter (a,b):
c = min (a,b)
d = max (a,b)
a = c
b = d
if (b%a) == 0:
print a
return a
gcdIter (a,b%a)
print gcdIter (a,b)
You are ignoring the return value for the recursive call:
gcdIter (a,b%a)
Recursive calls are no different from calls to other functions; you'd still need to do something with the result of that call if that is what you tried to produce. You need to pass on that return value with return
return gcdIter (a,b%a)
Note that you can assign to multiple targets when assigning:
def gcdIter(a, b):
a, b = min(a, b), max(a, b)
if b % a == 0:
return a
return gcdIter(a, b % a)
You really don't need to care about the bigger and smaller values here. A more compact version would be:
def gcd_iter(a, b):
return gcd_iter(b, a % b) if b else abs(a)

Categories

Resources