return True/False 实际做什么?(Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28513250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does return True/False actually do? (Python)
提问by HawkeyeNate
I've added in a sample code below just so you have a frame of reference for what my question actually is. I always see programs with if statements that return True or False, but what is actually happening here, why wouldn't you just want to put a print statement for false/true. I'm lost here.
我在下面添加了一个示例代码,以便您对我的问题实际上有一个参考框架。我总是看到带有返回 True 或 False 的 if 语句的程序,但是这里实际发生的情况,您为什么不只想为 false/true 放置一个打印语句。我在这里迷路了。
def false(x,y):
x > y
return False
false(9,10)
采纳答案by Andrew Magee
Because most of the time you'll want to do something with the result other than print it. By using a return value, the function does one thing: do the calculation, and the caller can do whatever it wants with it: print it, write it to a database, use it as part of some larger calculation, whatever. The idea is called composability.
因为大多数情况下,除了打印结果之外,您还想对结果做一些事情。通过使用返回值,该函数做一件事:进行计算,调用者可以用它做任何它想做的事情:打印它,将它写入数据库,将它用作一些更大计算的一部分,等等。这个想法被称为可组合性。
Also your example doesn't currently make much sense as it will always return False
after evaluating x > y
but doing nothing with the result. Perhaps you meant something like:
此外,您的示例目前没有多大意义,因为它总是False
在评估后返回,x > y
但对结果不做任何处理。也许你的意思是这样的:
def is_greater(x, y):
if x > y:
return True
else:
return False
Then is_greater
is something that can easily be used in whatever context you want. You could do:
然后is_greater
是可以在您想要的任何上下文中轻松使用的东西。你可以这样做:
x = is_greater(a, b)
write_to_super_secret_database(x)
(In real life you probably wouldn't use a function to do something so trivial, but hopefully the example makes sense.)
(在现实生活中,您可能不会使用函数来做如此微不足道的事情,但希望这个例子有意义。)
回答by Christian Sauer
Functions which return True / False are used in further statements like IF:
返回 True / False 的函数用于进一步的语句,如 IF:
Like this:
像这样:
def is_bigger(x,y):
return x > y
if is_bigger(10,9):
do_something
elif:
print "math don't work anymore"
you should take a look at variables and control structures: http://www.tutorialspoint.com/python/python_if_else.htm
你应该看看变量和控制结构:http: //www.tutorialspoint.com/python/python_if_else.htm