Python 函数返回值
一、函数返回值
返回值作用:
一旦函数调用或执行,那么函数外部的程序,就没办法控制函数的执行过程。此时外部程序只能等待函数执行结果
为什么要等待? 因为外部程序要根据函数的执行结果来决定下一步如何走,这个执行结果就以return 的形式返回给外部程序
return 代表一个函数的结果并结束该函数
return 可以返回任意数据类型
对于用户函数可以返回任意数量值,对于py本身来讲,函数只能返回一个值(处理的时候按元组进行返回。当作一个值返回)
如果未在函数中指定return. 那么这个函数的返回值为None
一个或多个返回值
def func():
"""
return a # 返回一个值
return a,b,c # 返回多个值,变量之间按逗号隔开,以元组的形式返回
:return:
"""
a = 111
b = [1, 2, 3]
c = {'a': 15, 'b': 6}
# return a
return a,b,c
print(func())
运行结果:
(111, [1, 2, 3], {'b': 6, 'a': 15})
没有返回值的函数
# 1.不写return时返回None
def func():
a=111
b=[1,2,3]
ret=func()
print(ret)
# 2.只写一个return时返回None
def func():
a=111
b=[1,2,3]
return
ret=func()
print(ret)
# 3.return None的时候返回None
def func():
a=111
b=[1,2,3]
return None
ret=func()
print(ret)
return 结束一个函数的执行
def func4():
print (1111111)
return #结束一个函数的执行
print (1242451)
func4()
定义一个列表,返回列表的最后一个值
# 方法一
def func():
list=['hello','egon',11,22]
return list[-1]
print(func())
运行结果:22
# 方法二
def func():
list=['hello','egon',11,22]
return list
m,n,k,g=func()#
print(g,n)
运行结果:22 egon
#定义全局变量
login_status = False
def auth():
"""
假装连上数据库. get data from db
:param username:
:param password:
:return:
"""
username = input("Please Input username:").strip()
password = input("Please Input password:").strip()
_username = "Harry"
_password = "287850394"
if username == _username and password == _password:
print("passed authentication")
return True
else:
return False
def home():
if login_status == True:
print("welcome to home page")
else:
print("authentication failure. Please login")
auth()
def pay():
if login_status == True:
print("welcome to pay page")
else:
print("authentication failure. Please login")
auth()
# 执行函数auth()并间执行结果返回给login_status全局变量
# 此处为了进行区分返回值的作用.可直接执行auth()进行对比
login_status = auth()
# auth()
home()
pay()
运行结果:
Please Input username:Harry
Please Input password:287850394
passed authentication
welcome to home page
welcome to pay page