简体   繁体   English

打印与返回 Python Function

[英]Print vs Return in Python Function

I am learning Python these days and I want to ask which code is better to write and applicable in real world or used in practice actually?这些天我正在学习 Python,我想问哪个代码更好地编写和适用于现实世界或实际用于实践? Both codes are giving the same output though.不过,这两个代码都给出了相同的 output。 In first function, I used return inside and then had to use print when it comes to invoking.在第一个 function 中,我在内部使用了 return,然后在调用时不得不使用 print。 While on the other hand, I used print inside and then just call the function.而另一方面,我在里面使用了 print,然后调用了 function。 So, which is a good practice?那么,哪个是好习惯呢?

And apart from that, many times I would need to get many things inside my function and I will have an option to either get it back through "print" and "return" - so also in those conditions, what should I do ideally and what is being used in practice?除此之外,很多时候我需要在我的 function 中获取很多东西,我可以选择通过“打印”和“返回”来取回它 - 所以在这些情况下,我应该做什么理想以及什么是在实践中使用吗?

def min_func(values):
    return min(values)
print(min_func([3, 41, 12, 9, 74, 15]))
def min_func(values):
    print(min(values))
min_func([3, 41, 12, 9, 74, 15])

It depends on what you want your function to do.这取决于您希望 function 做什么。

For example, if we create a function to print the minimum number from a list, we can do this:例如,如果我们创建一个 function 来打印列表中的最小数字,我们可以这样做:

def print_min(values):
    print(min(values))
print_min([3, 41, 12, 9, 74, 15])

Note that the function does not return any value.请注意,function 不返回任何值。 When you call this function, it will just print the value and return nothing.当您调用此 function 时,它只会打印该值并且不返回任何内容。 So, that value cannot be used later in the program.因此,该值不能在程序中稍后使用。

On the other hand, if you want your function to return the minimum number so that you can use it to do more processing later (and print some other output later), you can do:另一方面,如果您希望您的 function返回最小数字,以便以后可以使用它进行更多处理(并稍后打印一些其他 output),您可以执行以下操作:

def get_min(values):
    return min(values)
m = get_min([3, 41, 12, 9, 74, 15])

Now you may print it, or write it to a file, or do some mathematical operations on it.现在您可以打印它,或将其写入文件,或对其进行一些数学运算。 The return value is available for your program to use later.返回值可供您的程序稍后使用。

I think it is better to use the first approach you mentioned because it is more flexible to work with the value the function is returning and with the returned value you can do whatever you want我认为最好使用您提到的第一种方法,因为使用 function 返回的值更灵活,并且使用返回的值您可以做任何您想做的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM