Related
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:
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'
I've been tasked with something a bit unusual and unexpectedly puzzling - Display the source code of a particular class's implementation of a method.
In [1]: class Demonstration:
...: def cost():
...: return 42
...:
In [2]: class OtherDemo:
...: def cost():
...: return 43
...:
In this example, I'd want to find the text def cost(): and the following lines at the appropriate indent for either given class.
modules like inspect or dis are nearly what I'm looking for, but I want to display the python code, such as is displayed during a traceback; not bytecode.
I'm also not opposed to parsing the source files, either - is there a library that text editors might use for autocompletion or indent calculations that could find a specific method in a class?
It sounds like the inspect library is exactly what you need, in particular, the function getsourcelines:
In [1]: def foo(x):
...: x += 3
...: x += 4
...: return x
...:
In [2]: import inspect
In [3]: inspect.getsourcelines(foo)
Out[3]: (['def foo(x):\n', ' x += 3\n', ' x += 4\n', ' return x\n'], 1)
In [4]: source_code = _
In [6]: print(''.join(source_code[0]))
def foo(x):
x += 3
x += 4
return x
From the docs:
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.
In Python, because of the ability to dynamically modify anything it can be very tricky to map back to a source definition. The definition, after all, could be created on the fly.
Here's a somewhat simplistic example. Dynamic definitions can be much trickier even than this, and it's especially tricky if implementation occurs in a pre-compiled module.
def make_random_function(coin='Heads'):
if coin == 'Heads':
def foo(self, a):
print a
elif coin == 'Tails':
def foo(self, a, b):
return a + b
else:
def foo(self, *args, **kwargs):
raise ValueError('Invalid coin used to create function.')
foo.__name__ = "dynamic_foo"
foo.__doc__ = "Good luck buddy."
return foo
import random
val = random.random()
if val > 0.51:
coin = 'Heads'
elif val < 0.49:
coin = 'Tails'
else:
coin = 'Trick'
function = make_random_function(coin)
MyType = type("MyType", (object,), {function.__name__:function})
m = MyType()
When I run this and then call m.dynamic_foo() I see this:
In [313]: coin
Out[313]: 'Trick'
In [314]: val
Out[314]: 0.5099718112195031
In [315]: m.dynamic_foo()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-315-70b3caeb205b> in <module>()
----> 1 m.dynamic_foo()
<ipython-input-310-475ea0810d8d> in foo(*args, **kwargs)
8 else:
9 def foo(*args, **kwargs):
---> 10 raise ValueError('Invalid coin used to create function.')
11
12 foo.__name__ = "dynamic_foo"
ValueError: Invalid coin used to create function.
In [316]: m
Out[316]: <__main__.MyType at 0x7f37e70b3ad0>
Even if I use inspect.getsourcelines(m.dynamic_foo) it's a bit misleading:
In [319]: inspect.getsourcelines(m.dynamic_foo)
Out[319]:
([u' def foo(self, *args, **kwargs):\n',
u" raise ValueError('Invalid coin used to create function.')\n"],
9)
Notice how the function's source shows that its name is "foo" (not "dynamic_foo") and it's not a class method or instance method of MyType or anything. This is technically correct in the sense that it is the actual lines of source code, but it's not necessarily what someone might expect to see, since it's a definition that exists in a manner disconnected from how it gets dynamically injected into a class definition.
And this is a simple example of this kind of dynamic function creation and dynamic class manipulation. The more complicated this gets, the less reliable it is to count on inspecting source lines as a reasonable way to understand the function's implementation.
I'm now start learning python and I'm have problem with filter function.
If I run
list=list(range(10))
def f(x): return x % 2 != 0
print(((filter(f,list))))
I will get the result is
filter object at 0x00000000028B4E10
Process finished with exit code 0
And if I modify the code to
list=list(range(10))
def f(x): return x % 2 != 0
print(list(filter(f,list)))
The result I get will be
Traceback (most recent call last):
File "C:/Users/Vo Quang Hoa/PycharmProjects/HelloWorld/Hello.py", line 6, in <module>
print(list(filter(f,list)))
TypeError: 'list' object is not callable
Process finished with exit code 1
What's happend. How to get the list 1 3 5 7 9
Thank for your help.
You renamed list, giving it a different value. Don't do that, you shadowed the built-in type. Change your code to use a different name instead:
some_list = list(range(10))
def f(x): return x % 2 != 0
print(list(filter(f, some_list)))
and then filter() works just fine.
Your main problem is that you called your list variable, um, list. You must not use the same name as other objects! Call your list something else, and/or use a naming convention like upper camel case;
Fred=list(range(10))
def f(x): return x % 2 != 0
print(list(filter(f,Fred)))
I hope this help to you
ran=range(10)
def f(x): return x % 2 != 0
res = filter(f,ran)
for i in res:
print(i,end=' ')
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'