I'm using Python 2.7.11 on Debian Linux.
I have two functions, one which works exactly as expected with a normal function call, and another that works well enough except for the fact that a normal function call doesn't work on this second function; I have to put a print in front of the function in order to get it to work.
1) The first function, executing as expected with a normal function call:
def print_me(string):
print string
print_me("I am a string")
2)The second function, which does NOT work with a normal function call:
def fruit_color(fruit):
fruit = fruit.lower()
if fruit == 'apple':
return 'red'
elif fruit == 'banana':
return 'yellow'
elif fruit == 'pear':
return 'green'
else:
return 'Fruit not recognized'
3) A normal function call, ie, fruit_color('apple'), doesn't work. I instead have to place print in front of the function in order to get it to work:
print fruit_color('apple')
4)Now that I've (hopefully) explained myself succinctly enough, I will restate my question: Why is the function call working for the print_me function but not for the fruit_color function?
print_me
actually prints a string, which is what you're seeing. fruit_color
just returns a string value, which you could then do whatever you want to it - assign it to a variable, manipulate it, or, in this case, print it by calling print
.
print and return functions are different overall.
def print_me(string):
print string
print_me('abc')
output:
abc
def return_me(string):
return string
return_me('abc')
OUTPUT:
No output
Because print function in python prints the argument passed. while, return function will return the argument. So that we can use it some where else in the program if needed.
Because fruit_color
function only returns string. It doesn't print. you need to call it with print
if you want to print the value returned by this function.
Aha! Now I get it! For what I was doing it would've been better to use print inside the fruit_color function, so that I could simply call it:
def fruit_color(fruit):
fruit.lower()
if fruit == 'apple':
print 'green'
fruit_color('apple')
Thanks to all!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.