Return value of Python function

51CTO 2022-05-14 15:53:09 阅读数:692

returnvaluepythonfunction



Python The return value of the function

  • ​​ One 、 Preface ​​
  • ​​ Two 、 Return value syntax format ​​
  • ​​ 3、 ... and 、 Return value syntax instance ​​

One 、 Preface

We create functions that just do something for us , When it's done, it's over . But actually , Sometimes we need to get the results of things . It's like a supervisor giving orders to junior staff , Staff to do it , Finally, the results need to be reported to the supervisor , The purpose of setting the return value for a function is to return the processing result of the function to the calling program .


Two 、 Return value syntax format

stay Python in , Can be used inside a function return Statement specifies a return value for a function . The return value can be of any type , And no matter return Where does the statement appear in the function , As long as it's implemented , It will directly end the execution of the function .

return The syntax format of the statement is as follows :

result = return [ value]
  • 1.

Parameter description :

  • result: Used to save returned results , If it's a value , that result What is saved in is a value returned , The value can be of any type . If multiple values are returned , that result A tuple is stored in .
  • value: Optional parameters , Used to specify the value to return , Can return a value , Multiple values can also be returned .


explain : When there is no return When the sentence is , Or omitted return Statement , Will return None, Return null value .



3、 ... and 、 Return value syntax instance

for example , Define a function , Used according to the name entered by the user , Get its nickname , Then call the function outside the function , And get the return value , The code is as follows :

def fun_checkout( name):
nickName = ""
if name == " Xiaohong ": # If the input is Xiao Hong
nickName = " The demon "
elif name == " Xiao Ming ":
nickName = " unhappy "
elif name == " Xiao Cong ":
nickName = " No head "
else:
nickName = " The information you entered cannot be found "

return nickName # Returns the nickname of the corresponding person's name


# ****************** Call function ******************** #

while True:
name = input( " Please enter the name of the person you want to query ") # Receive user input
nickname = fun_checkout( name) # Call function
print( " full name :", name, " nickname :", nickname)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

The running results are as follows :

Python The return value of the function _ The body of the function



版权声明:本文为[51CTO]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141525033866.html