This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 8 months ago.
In my previous question, Andrew Jaffe writes:
In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something.
When you create autoparts() or splittext(), the idea is that this will be a function that you can call, and it can (and should) give something back.
Once you figure out the output that you want your function to have, you need to put it in a return statement.
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
print(parts_dict)
>>> autoparts()
{'part A': 1, 'part B': 2, ...}
This function creates a dictionary, but it does not return something. However, since I added the print, the output of the function is shown when I run the function. What is the difference between returning something and printing it?
print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:
my_auto_parts = autoparts()
print(my_auto_parts['engine'])
See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.
For a good tutorial, check out dive into python. It's free and very easy to follow.
The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable once the function is finished.
>>> def foo():
... print "Hello, world!"
...
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
... return "Hello, world!"
...
>>> a = foo()
>>> a
'Hello, world!'
Or in the context of returning a dictionary:
>>> def foo():
... print {'a' : 1, 'b' : 2}
...
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
... return {'a' : 1, 'b' : 2}
...
>>> a = foo()
>>> a
{'a': 1, 'b': 2}
(The statements where nothing is printed out after a line is executed means the last statement returned None)
I think you're confused because you're running from the REPL, which automatically prints out the value returned when you call a function. In that case, you do get identical output whether you have a function that creates a value, prints it, and throws it away, or you have a function that creates a value and returns it, letting the REPL print it.
However, these are very much not the same thing, as you will realize when you call autoparts with another function that wants to do something with the value that autoparts creates.
you just add a return statement...
def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
printing out only prints out to the standard output (screen) of the application. You can also return multiple things by separating them with commas:
return parts_dict, list_of_parts
to use it:
test_dict = {}
test_dict = autoparts()
Major difference:
Calling print will immediately make your program write out text for you to see. Use print when you want to show a value to a human.
return is a keyword. When a return statement is reached, Python will stop the execution of the current function, sending a value out to where the function was called. Use return when you want to send a value from one point in your code to another.
Using return changes the flow of the program. Using print does not.
A function is, at a basic level, a block of code that can executed, not when written, but when called. So let's say I have the following piece of code, which is a simple multiplication function:
def multiply(x,y):
return x * y
So if I called the function with multiply(2,3), it would return the value 6. If I modified the function so it looks like this:
def multiply(x,y):
print(x*y)
return x*y
...then the output is as you would expect, the number 6 printed. However, the difference between these two statements is that print merely shows something on the console, but return "gives something back" to whatever called it, which is often a variable. The variable is then assigned the value of the return statement in the function that it called. Here is an example in the python shell:
>>> def multiply(x,y):
return x*y
>>> multiply(2,3) #no variable assignment
6
>>> answer = multiply(2,3) #answer = whatever the function returns
>>> answer
6
So now the function has returned the result of calling the function to the place where it was called from, which is a variable called 'answer' in this case.
This does much more than simply printing the result, because you can then access it again. Here is an example of the function using return statements:
>>> x = int(input("Enter a number: "))
Enter a number: 5
>>> y = int(input("Enter another number: "))
Enter another number: 6
>>> answer = multiply(x,y)
>>> print("Your answer is {}".format(answer)
Your answer is 30
So it basically stores the result of calling a function in a variable.
def add(x, y):
return x+y
That way it can then become a variable.
sum = add(3, 5)
print(sum)
But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.
Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.
I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.
On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.
return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user.
Consider these two programs:
def function_that_prints():
print "I printed"
def function_that_returns():
return "I returned"
f1 = function_that_prints()
f2 = function_that_returns()
print "Now let us see what the values of f1 and f2 are"
print f1 --->None
print f2---->"I returned"
When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.
When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"
The below examples might help understand:
def add_nums1(x,y):
print(x+y)
def add_nums2(x,y):
return x+y
#----Function output is usable for further processing
add_nums2(10,20)/2
15.0
#----Function output can't be used further (gives TypeError)
add_nums1(10,20)/2
30
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-124-e11302d7195e> in <module>
----> 1 add_nums1(10,20)/2
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 4 years ago.
I have defined a function as follows:
def lyrics():
print "The very first line"
print lyrics()
However why does the output return None:
The very first line
None
Because there are two print statements. First is inside function and second is outside function. When a function doesn't return anything, it implicitly returns None.
Use return statement at end of function to return value.
e.g.:
Return None.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
Because of double print function. I suggest you to use return instead of print inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
This question already has answers here:
Why does [1].append(2) evaluate to None instead of [1,2]? [duplicate]
(2 answers)
Closed 6 years ago.
Please explain why c = None in the following Python 3 example, from the Python command line.
>>> a = [1,2]
>>> b = a
>>> c = b.append(3)
>>> print(a,b,c)
[1, 2, 3] [1, 2, 3] None
list.append() appends the entry in place and returns nothing which Python takes as None (default behavior of Python). For example:
>>> def foo():
... print "I am in Foo()"
... # returns nothing
...
>>> c = foo() # function call
I am in Foo()
>>> c == None
True # treated as true
You are assigning the return value of append which is None.
>>> a = [1,2]
>>> b = a.append(3)
>>> b == None
True
>>>
The function append doesn't return anything, that's why you have none in the variable. Let's see it better with a little example:
Let's say you have this function
def foo:
bar = "Return this string"
return bar
x = foo()
print(x) # x will be "Return this string"
Now let's say you have this function instead
def foo(bar):
print(bar)
x = foo(33) # Here 33 will be printed to the console, but x will be None
This happens because the return statement on the function, if you don't have any, the function will return None.
append is a function to do something in the list that you're calling it in (in Python strings are lists too), and this function doesn't need to return anything, it only modifies the list.
This question already has answers here:
Python function as a function argument?
(10 answers)
Closed 6 years ago.
def example(function):
if input() == "Hello there!":
#at this point I want to call the function entered in the tuples
an example of what I mean:
def example(function):
if input() == "Hello there!":
#do the function here
def Printer(What_to_print):
print(What_to_print + "Just an example")
example(Printer)
Is this possibe and are there drawbacks in doing this?
Yes. It is possible.
def example(function):
if input() == "Hello there!":
function("Hello there!") # invoke it!
Actually you can pass def functions and lambda functions as parameters and invoke them by () syntax.
In python, functions are objects like any other common types, like ints and strs. Therefore, there is no problem with a function that receives another function as an argument.
>>> def pr(): print ('yay')
>>> def func(f): f()
>>> isinstance(pr, object)
True
>>> isinstance(int, object)
True
>>> func(pr)
yay
>>>
def example(function, what_to_print):
if raw_input() == "Hello there!":
function(what_to_print)
def printer(what_to_print):
print(what_to_print + "Just an example")
example(printer, "")
My question is for below code why None is getting print in place of function output and why function output is getting before its position.
def print_spam():
print('spam')
def do_twice(r,ps):
g = ps()
print(r,'is a',g)
print(r,'is a',ps())
do_twice('xyz',print_spam)
Output is
spam
xyz is a None
spam
xyz is a None
The function print_spam() does not return anything. It just prints a statement.
Change it to:
def print_spam():
print('spam')
return 'spam'
Because your function doesn't return anything, it defaults to None. Now when assigning the function output to g, it will contain the returned string of the function (spam).
Consider replacing
g = ps()
print(r,'is a',g)
with
g = ps
print r,'is a',
g()
anyway, as pointed out by some other answers, print_spam() returns None