退货和打印python之间的区别? [英] Difference between returns and printing in 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,代替函数的位置
示例时间 ($) In python I don't seem to be understanding the return function. Why use it when I could just print it? This code gives me 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 Break down Example Time
这篇关于退货和打印python之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$当函数ret返回
>>>时,$ b 4 + ret()#ret()被替换为数字3。 7
4 + pri()#pri()打印3并隐式返回无法添加的
>>> 3
>>> TypeError不能添加int和NoneType
def maximum(x, y):
if x > y:
print(x)
elif x == y:
print('The numbers are equal')
else:
print(y)
maximum(2, 3)
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))
if
else
constructs). It is what lets you "take data with you between function calls".
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.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