退货和打印python之间的区别? [英] Difference between returns and printing in python?

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

问题描述

在python中,我似乎并不了解返回函数。为什么在打印时使用它?

  def maximum(x,y):
if x> y:
print(x)
elif x == y:
print('数字相等')
else:
print(y)$ b $ (2,3)

这段代码给我 3

  def maximum(x,y):
if x> y:
return x
elif x == y:
return'数字相等'
else:
return y

print (最大(2,3))

那么两者有什么区别呢?

解决方案

关键



返回不是函数。它是一个控制流构造(如 if if else 构造)。这是什么让你在函数调用之间与你取数据。



细分




  • print :将值赋给 user 作为输出字符串。 print(3)会在屏幕上显示一个字符串'3',供用户查看。该程序将失去价值。

  • return :将值赋给程序的。然后函数的调用者拥有实际的数据和数据类型(bool,int等等)。 return 3 的值将是3,代替函数的位置




示例时间 ($)



$当函数ret返回
>>>时,$ b 4 + ret()#ret()被替换为数字3。 7
4 + pri()#pri()打印3并隐式返回无法添加的
>>> 3
>>> TypeError不能添加int和NoneType


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)

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!

解决方案

The Point

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".

Break down

  • 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: 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.

Example Time

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天全站免登陆