函数体系
接下来,我们将按照这个函数体系给大家详细的介绍函数:
如果现在有一个需求需要实现用户登录注册的功能,我们该怎么实现呢?
# 注册
username = input('username: ').strip()
pwd = input('password: ').strip()
with open('38a.txt', 'a', encoding='utf8') as fa:
fa.write(f"{username}:{pwd}\n")
fa.flush()
# 登录
inp_username = input('username: ').strip()
inp_pwd = input('password: ').strip()
with open('38a.txt', 'rt', encoding='utf8') as fr:
for user_info in fr:
user_info = user_info.strip('\n')
user_info_list = user_info.split(':')
if inp_username == user_info_list[0] and inp_pwd == user_info_list[1]:
print('login successful')
break
else:
print('failed')
假设现在你是下水道工,如果你事先准备好你的工具箱,等你接到修理下水道的工作的时候,你直接把你的工具箱拿过去直接使用就行了,而不需要临时准备锤子啥的。
在程序中,函数就是具备某一功能的工具,事先将工具准备好就是函数的定义,遇到应用场景拿来就用就是函数的调用。
如果不使用函数,写程序时将会遇到这三个问题:
先定义函数,后调用。
def 函数名(param1、param2……):
"""
函数功能的描述信息
:param1:描述
:param2:描述
:return:返回值
"""
code 1
code 2
code 3
...
return 返回值
函数名(param1、param2……)
# 注册功能函数
def register():
"""注册功能"""
username = input('username: ').strip()
pwd = input('password: ').strip()
with open('38a.txt', 'a', encoding='utf8') as fa:
fa.write(f"{username}:{pwd}\n")
fa.flush()
register()
# 复用
register()
register()
# 登录功能函数
def login():
"""登录功能"""
inp_username = input('username: ').strip()
inp_pwd = input('password: ').strip()
with open('38a.txt', 'rt', encoding='utf8') as fr:
for user_info in fr:
user_info = user_info.strip('\n')
user_info_list = user_info.split(':')
if inp_username == user_info_list[0] and inp_pwd == user_info_list[1]:
print('login successful')
break
else:
print('failed')
login()
def func():
bar() # 不属于语法错误,不会报错
print('*'*10)
def bar():
print('from bar')
def foo():
print('from foo')
bar()
foo()
'''
from foo
from bar
'''
def foo():
print('from foo')
bar()
def bar():
print('from bar')
foo()
'''
from foo
from bar
'''
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有