【问题标题】:Python 2.7.11:Why does a function call work for one function but not for another?Python 2.7.11:为什么函数调用对一个函数起作用,而对另一个函数不起作用?
【发布时间】:2016-05-20 18:52:13
【问题描述】:

我在 Debian Linux 上使用 Python 2.7.11。

我有两个函数,一个与普通函数调用完全一样,另一个运行良好,除了普通函数调用不适用于第二个函数;我必须在函数前面放一个 print 才能让它工作。

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

def print_me(string):

    print string

    print_me("I am a string")

2)第二个函数,它不适用于普通函数调用:

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) 正常的函数调用,即fruit_color('apple'),不起作用。相反,我必须将 print 放在函数前面才能使其工作:

print fruit_color('apple')

4) 既然我已经(希望)简洁地解释了自己,我将重申我的问题:为什么函数调用适用于 print_me 函数而不适用于 fruit_color 函数?

【问题讨论】:

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

标签: python function call


【解决方案1】:

print_me 实际上打印了一个字符串,这就是您所看到的。 fruit_color 只返回一个字符串值,然后你可以对它做任何你想做的事情 - 将它分配给一个变量,操作它,或者在这种情况下,通过调用 print 来打印它。

【讨论】:

    【解决方案2】:

    打印和返回功能总体上是不同的。

    def print_me(string):
        print string
    
    print_me('abc')
    

    输出:

    abc

    def return_me(string):
        return string
    
    return_me('abc')
    

    输出:

    没有输出

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        啊哈!现在我懂了!对于我正在做的事情,最好在fruit_color 中使用print,这样我就可以简单地调用它:

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

        谢谢大家!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-24
          • 2019-01-17
          • 2020-03-11
          • 1970-01-01
          • 2019-01-24
          • 1970-01-01
          相关资源
          最近更新 更多