table of Contents
Defined functions
What is the function
Is a kind of utility functions have a function, the tool is ready to advance is the definition of the function, the scene brought on by experience.
How to use the function
def 函数名(等同于变量)(): # 定义函数
"""对函数的描述"""
代码块
函数名() # 函数调用
Registration function function
def register():
"""注册功能"""
count = 0
while count < 3:
username_inp = input('请输入你的用户名:').strip()
pwd_inp = input('请输入你的密码:').strip()
re_pwd_inp = input('请再次确认你的密码:').strip()
if re_pwd_inp != pwd_inp:
print('两次密码输入不一致!')
count += 1
continue
with open('userinfo.txt', 'a', encoding='utf-8') as fa:
fa.write(f'{username_inp}:{pwd_inp}\n')
print('注册成功')
break
register()
Login performance function
def login():
"""登录功能"""
username_inp = input('请输入你的用户名:').strip()
pwd_inp = input('请输入你的密码:').strip()
user_info = f'{username_inp}:{pwd_inp}'
with open('userinfo.txt', 'r', encoding='utf-8') as fr:
data = fr.read()
user_info_list = data.split('\n')
if user_info in user_info_list:
print('登录成功')
else:
print('登陆失败')
login()
Three forms defined functions
Empty function
It defines a function, but nothing in the
def func():
pass
There are function parameters
def add(x, y):
"""有参函数"""
print(int(x) + int(y))
add(1, 2)
No-argument function
def func():
print('hello world')
Call functions
Use 函数名()
the form can call the function
def func(x, y):
"""给定两个数, 打印较大的数"""
if x > y:
print(x)
else:
print(y)
print(func)
func(10, 20) # 加括号就能调用(执行内存中的代码)
# 打印结果:
<function func at 0x00000253DFEF0950> # 函数的地址
20
Function's return value
return to return a value
def add(x, y):
return x + y
res = add(1, 2)
print(res)
# 打印结果
3
return no return value, default return None
def add(x, y):
print(x, y)
# return x + y
res = add(1, 2)
print(res)
# 打印结果:
1 2
None
return can return multiple values, you can return any data type, default return form tuple
def add(x, y):
print(2)
return x, y, x + y
res = add(1, 2)
print(res)
# 打印结果:
2
(1, 2, 3)
return terminates the function, the following code does not run, even if there are multiple return, only the implementation of a return, not to the next
def add(x, y):
print(2)
return x, y, x + y # 遇到return就会终止函数
print('hello world')
return x
res = add(1, 2)
print(res)
# 打印结果:
2
(1, 2, 3)
Function parameters
And parameter arguments
Katachisan
Parameters defined in parentheses function definition stage, called the formal parameters, parameter referred to, is essentially the variable name
def func(x, y):
print(x)
print(y)
Arguments
Passed in the function call stage parentheses parameter, called the argument
func(1, 2)
Positional parameters
Location parameter
In the definition phase function, the parameters in the order from left to right are sequentially defined, called the position parameter
def func(x, y):
print(x)
print(y)
Argument position
Function call stage, according to the parameters defined in the order from left to right, a position called actual parameter value to sequentially pass the position parameter
func(1, 2)
The default parameter
In the function definition stage, it has been assigned
def func(x, y=10):
print(x)
print(y)
func(2)
- During the definition phase has been assigned, you can not pass value when you call; if by value, use value pass
- After the necessary parameter default position parameter
Keyword argument
When calling the function, according to the location name to the value of the parameter
func(y=2, x=1)
Keyword argument must be in position behind the argument
Vararg
The variable length parameter of *
* Parameter will overflow in the position-all argument, and then stored tuple, the tuple is then assigned to the parameters *. Note that: * the name of the parameter convention for the args.
def f1(*args):
print('args:', args)
f1(1, 23, 4) # args接收位置实参多余的参数
# 打印结果:
args: (1, 23, 4)
The variable length parameter **
'''
形参中的**会将溢出的关键字实参全部接收,然后存储字典的形式,然后把字典赋值给**后的参数。需要注意的是:**后的参数名约定俗成为kwargs。
'''
def f2(a,**kwargs):
print('kwargs:', kwargs)
f2(x=12, a=10, b=9) # kwargs接收关键字实参多余的参数
# 打印结果:
kwargs: {'x': 12, 'b': 9}
Variable-length argument of *
def func1(a,b,c,d):
print(a,b,c,d)
lt = [1,2,3,4]
func1(*lt) # *lt列表中的元素打散成位置实参依次传给位置形参
** of arguments variable
def func(a, b):
print(a, b)
dic = {'a': 1, 'b': 2}
func(**dic) # **dic把字典打散成关键字实参然后传给函数func