Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7.11:Why does a function call work for one function but not for another?

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, i.e., 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?

like image 868
MadHatter Avatar asked Sep 13 '26 03:09

MadHatter


1 Answers

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.

like image 121
Mureinik Avatar answered Sep 15 '26 17:09

Mureinik