使用函数:打印与返回 [英] using functions: print vs return

查看:41
本文介绍了使用函数:打印与返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 脚本中使用函数中的数据的正确方法是什么?

What is correct way to use data from functions in Python scripts?

使用 print ,例如:

var1 = 'This is var1'

def func1():
  print(var1)

func1()

或-带返回:

var1 = 'This is var1'

def func1(): 
  return var1

print(func1())

两者给出相同的结果:

$ ./func_var_print_return.py
This is var1

推荐答案

当函数的目的是产生值时,您应该返回一个值.这样,功能可以使用其他功能.例如

You should return a value when the purpose of the function is to produce a value. This is so functions can use other functions. For example

def add(x,y):
    return x + y

def multiply(a,b):
    product = 0
    for i in range(b):
        product = add(product, a)   # Note I am calling the add function
    return product

测试

>>> multiply(5,4)
20

请注意,我在 multiply 函数中使用了 add 中的 return 值.如果我只打印 add 中的值,那我将无法做到这一点.

Note that I used the return value from add within my multiply function. If I only printed the value from add, I would have been unable to do that.

这篇关于使用函数:打印与返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆