我在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函数无效?
总体而言,打印和返回功能有所不同。
def print_me(string):
print string
print_me('abc')
输出:
abc
def return_me(string):
return string
return_me('abc')
输出:
无输出
因为python中的print函数会打印传递的参数。而return函数将返回参数。这样我们就可以在程序中其他需要的地方使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句