接下来,咱们将按照这个函数体系给你们详细的介绍函数:编程
若是如今有一个需求须要实现用户登陆注册的功能,咱们该怎么实现呢?函数式编程
# 注册 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')
假设如今你是下水道工,若是你事先准备好你的工具箱,等你接到修理下水道的工做的时候,你直接把你的工具箱拿过去直接使用就好了,而不须要临时准备锤子啥的。函数
在程序中,函数就是具有某一功能的工具,事先将工具准备好就是函数的定义,遇到应用场景拿来就用就是函数的调用,因此须要注意的是:工具
若是不使用函数,写程序时将会遇到这三个问题:code
先定义函数,后调用。协程
def 函数名(param一、param2……): """ 函数功能的描述信息 :param1:描述 :param2:描述 :return:返回值 """ code 1 code 2 code 3 ... return 返回值
函数名(param一、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 '''