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.
Related
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 7 months ago.
I am trying to return the function with arguments and the functions results in the format of the print statement. The code works except I am getting a "None" between each answer when a test is run. How do I prevent the None from printing?
def debug(func):
"""
:param func: function
"""
def inner_func(*args,**kwargs):
answer = func(*args,**kwargs)
return print(f"{func.__name__}{args} was called and returned {answer}")
return inner_func
And the test:
def add(a, b):
return a + b
#debug
def sub(a, b=100):
return a - b
print(add(3, 4))
print(sub(3))`
print(sub(3,4))
add(3, 4) was called and returned 7
None
sub(3,) was called and returned -97
None
sub(3, 4) was called and returned -1
None
Expected Output:
add(3, 4) was called and returned 7
sub(3) was called and returned -97
sub(3, 4) was called and returned -1
I think you meant to write your debug decorator like this:
(properly indented)
def debug(func):
"""
:param func: function
"""
def inner_func(*args,**kwargs):
answer = func(*args,**kwargs)
print(f"{func.__name__}{args} was called and returned {answer}")
return answer
return inner_func
You meant to return answer rather than the result of a print() which is always None.
Also, if you don't want to see the returned answer, then don't print it. Since the decorator calls print(), just call the functions:
add(3, 4)
sub(3)
sub(3,4)
Also, in particular, if you want this line:
sub(3) was called and returned -97
you can change the print line to this:
print(f"{func.__name__}({','.join([str(arg) for arg in args])}) was called and returned {answer}")
This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
If I had a function that I made:
def a():
n = 2*2
How could I access n out of the function without calling a?
You cannot. You will need to define the variable outside of the function, or call the function and return it.
You need to return it, so do:
def a():
n = 2*2
return n
print(a())
Output:
4
You can also do print, but return is better, check this: What is the formal difference between "print" and "return"?
This question already has answers here:
Can one function have multiple names?
(3 answers)
Closed 5 years ago.
I wold like to use same method but two different names.
For example:
def func(a):
print a
def func2(a):
print a
n= "yes"
func(n)
func2(n)
answer should be:
"yes"
"yes"
Would there be any way I can do:
def fun(a) or func2(a):
print a
or something like this?
Python functions are just objects, you can assign one to another name:
def fun(a):
print a
func2 = fun
Now the names func2 and fun reference the same function object, you can call it through either name.
def func(a):
print("a")
n= "yes"
def fun(a):
func(a)
func(n)
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()
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 7 years ago.
In python I don't seem to be understanding the return function. Why use it when I could just print it?
def maximum(x, y):
if x > y:
print(x)
elif x == y:
print('The numbers are equal')
else:
print(y)
maximum(2, 3)
This code gives me 3. But using return it does the same exact thing.
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
So what's the difference between the two? Sorry for the mega noob question!
The Point
return is not a function. It is a control flow construct (like if else constructs). It is what lets you "take data with you between function calls".
Break down
print: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.
return: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.
Example Time
def ret():
return 3
def pri():
print(3)
4 + ret() # ret() is replaced with the number 3 when the function ret returns
# >>> 7
4 + pri() # pri() prints 3 and implicitly returns None which can't be added
# >>> 3
# >>> TypeError cannot add int and NoneType
What would you do if you need to save printed value? Have a look at good explanation in docs and cf.:
>>> def ret():
return 42
>>> def pri():
print(42)
>>> answer = pri()
42
>>> print(answer) # pri implicitly return None since it doesn't have return statement
None
>>> answer = ret()
>>> answer
42
It also is no different from return statement in any other language.
For more complex calculations, you need to return intermediate values. For instance:
print minimum(3, maximum(4, 6))
You can't have maximum printing its result in that case.
Remember that the interactive command line isn't the only place methods will be called from. Methods can also be called by other methods, and in that case print isn't a usable way to pass data between them
Honestly, it depends on what you need the function to do. If the function specification state that it will print out max term, then what you have is fine. What generally happens for a method like this is that the method should return the actual value which is larger. In the case they are equal, it doesn't matter which value is returned.