Python 2.7.11:为什么函数调用对一个函数有效,而对另一个函数无效?

Python 2.7.11:为什么函数调用对一个函数有效,而对另一个函数无效?,python,function,call,Python,Function,Call,我正在DebianLinux上使用Python 2.7.11 我有两个函数,一个与普通函数调用完全一样,另一个工作得很好,只是普通函数调用在第二个函数上不起作用;我必须在函数前面打印一个字,才能让它工作 1) 第一个函数,通过正常函数调用按预期执行: def print_me(string): print string print_me("I am a string") def fruit_color(fruit): fruit = fruit.lower()

我正在DebianLinux上使用Python 2.7.11

我有两个函数,一个与普通函数调用完全一样,另一个工作得很好,只是普通函数调用在第二个函数上不起作用;我必须在函数前面打印一个字,才能让它工作

1) 第一个函数,通过正常函数调用按预期执行:

def print_me(string):

    print string

    print_me("I am a string")
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'
2) 第二个函数不适用于正常函数调用:

def print_me(string):

    print string

    print_me("I am a string")
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) 正常的函数调用,即水果颜色(“苹果”)不起作用。相反,我必须将打印放在函数前面,以使其正常工作:

print fruit_color('apple')

4) 现在我已经(希望)足够简洁地解释了我自己,我将重申我的问题:为什么函数调用适用于print\u me函数而不适用于fruit\u color函数

print\u me
实际上是打印一个字符串,这就是您看到的
FROUT\U color
只返回一个字符串值,然后您可以对其执行任何操作—将其分配给变量,对其进行操作,或者在本例中,通过调用
print

打印它,因为
FROUT\U color
函数只返回字符串。它不打印。如果要打印此函数返回的值,需要使用
print
调用它。

打印和返回函数总体上是不同的

def print_me(string):
    print string

print_me('abc')
输出:

abc

输出:

无输出


因为python中的print函数打印传递的参数。而return函数将返回参数。这样,如果需要,我们可以在程序的其他地方使用它。

啊哈!现在我明白了!对于我正在做的事情,最好在fruit_color函数中使用print,这样我就可以简单地称之为:

    def fruit_color(fruit):
        fruit.lower()
        if fruit == 'apple':
            print 'green'

    fruit_color('apple')

谢谢大家

print
打印它,
return
不打印它,所以需要显式打印返回值。