python中返回和打印之间的区别? [英] Difference between returns and printing in python?

查看:23
本文介绍了python中返回和打印之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中,我似乎不理解返回函数.当我可以打印时为什么要使用它?

In python I don't seem to be understanding the return function. Why use it when I could just print it?

def maximum(x, y):
    if x > y:
        print(x)
    elif x == y:
        print('The numbers are equal')
    else:
        print(y)

maximum(2, 3)

这段代码给了我3.但是使用 return 可以做同样的事情.

This code gives me 3. But using return it does the same exact thing.

def maximum(x, y):
    if x > y:
        return x
    elif x == y:
        return 'The numbers are equal'
    else:
        return y

print(maximum(2, 3))

那么两者有什么区别呢?抱歉我的超级菜鸟问题!

So what's the difference between the two? Sorry for the mega noob question!

推荐答案

重点

return 不是函数.它是一个控制流结构(类似于 if else 结构).它让您在函数调用之间随身携带数据".

return is not a function. It is a control flow construct (like if else constructs). It is what lets you "take data with you between function calls".

分解

  • print:将值作为输出字符串提供给 user.print(3) 会给屏幕一个字符串 '3' 供用户查看.程序将失去价值.

  • print: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.

return:给程序赋值.然后,函数的调用者拥有实际数据和数据类型(bool、int 等...)return 3 会将值 3 放在调用函数的位置.

return: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.

示例时间

def ret():
    return 3

def pri():
    print(3)

4 + ret() # ret() is replaced with the number 3 when the function ret returns
# >>> 7
4 + pri() # pri() prints 3 and implicitly returns None which can't be added
# >>> 3
# >>> TypeError cannot add int and NoneType

这篇关于python中返回和打印之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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