def 函数名(参数1,参数2,参数3,...): 函数体 return 返回的值 函数名() 注意:函数名要能反映其意义
示例:
def func(): #函数的定义 print("Hello wprld") func() #函数的调用(调用就是函数名加上括号)
return语句【表达式】退出函数(结束一个函数的执行),选择性地向调用方返回一个表达式。
返回值可以是任意数据类型。
如果函数有返回值,必须使用变量接收才有效果。
返回值情况:
1,返回值为None的情况
当不写return时,默认返回值为None
return不加参数时,返回None
return None
2,返回值不为None的情况
返回一个值: return xxx 返回一个值(一个变量) 任意数据类型
返回多个值: return a,b,[1,2,3] ; 用一个变量接收时返回的是一个元祖,也可以用相应数量的变量去接收, 可以返回任意多个、任意数据类型的值
示例:
不写return时,默认返回值为None def func(): #函数定义 s ="hello world" print(s) str = func() #函数调用 print(‘str: %s‘%str) #因为没有返回值,此时的str_len为None 运行结果: hello world str: None return不加参数时,返回None def func(): s ="hello world" print(s) return str = func() print(‘str: %s‘%str) 运行结果: hello world str: None return None def func(): s ="hello world" print(s) return None str = func() print(‘str: %s‘%str) 运行结果: hello world str: None 返回一个值 def func(): s ="hello world" print(s) return s str = func() print(‘str: %s‘%str) 运行结果: hello world str: hello world 返回多个值 def func(): s ="hello world" s1 = ‘hi‘ print(s) return 1,2 str = func() print(str) 运行结果: hello world (1, 2) def func(): s ="hello world" s1 = ‘hi‘ print(s) return 1,2 str1,str2 = func() print(str1,str2) 运行结果: hello world 1 2
原文:https://www.cnblogs.com/kumunotes/p/10589582.html