Python 2.7.11:为什么一个函数调用对一个函数起作用而对另一个函数不起作用?
Python 2.7.11:Why does a function call work for one function but not for another?
我在 Debian Linux.
上使用 Python 2.7.11
我有两个函数,一个在普通函数调用中完全按照预期工作,另一个工作得很好,除了普通函数调用在第二个函数上不起作用;为了让它工作,我必须在函数前面放一个打印。
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_me
实际上打印了一个字符串,这就是您所看到的。 fruit_color
只是 returns 一个字符串值,然后你可以对它做任何你想做的事——将它赋给一个变量,对其进行操作,或者在这种情况下,通过调用 print
打印它.
因为fruit_color
函数只有returns字符串。它不打印。如果要打印此函数返回的值,则需要使用 print
调用它。
print 和 return 函数总体上是不同的。
def print_me(string):
print string
print_me('abc')
输出:
abc
def return_me(string):
return string
return_me('abc')
输出:
无输出
因为 python 中的 print 函数打印传递的参数。而 return 函数将 return 参数。这样我们就可以在需要时在程序的其他地方使用它。
啊哈!现在我懂了!对于我所做的,最好在 fruit_color
中使用 print
,这样我就可以简单地调用它:
def fruit_color(fruit):
fruit.lower()
if fruit == 'apple':
print 'green'
fruit_color('apple')
感谢大家!
我在 Debian Linux.
上使用 Python 2.7.11我有两个函数,一个在普通函数调用中完全按照预期工作,另一个工作得很好,除了普通函数调用在第二个函数上不起作用;为了让它工作,我必须在函数前面放一个打印。
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_me
实际上打印了一个字符串,这就是您所看到的。 fruit_color
只是 returns 一个字符串值,然后你可以对它做任何你想做的事——将它赋给一个变量,对其进行操作,或者在这种情况下,通过调用 print
打印它.
因为fruit_color
函数只有returns字符串。它不打印。如果要打印此函数返回的值,则需要使用 print
调用它。
print 和 return 函数总体上是不同的。
def print_me(string):
print string
print_me('abc')
输出:
abc
def return_me(string):
return string
return_me('abc')
输出:
无输出
因为 python 中的 print 函数打印传递的参数。而 return 函数将 return 参数。这样我们就可以在需要时在程序的其他地方使用它。
啊哈!现在我懂了!对于我所做的,最好在 fruit_color
中使用 print
,这样我就可以简单地调用它:
def fruit_color(fruit):
fruit.lower()
if fruit == 'apple':
print 'green'
fruit_color('apple')
感谢大家!