Article directory
1. Getting to know functions
Function: It is an organized, reusable code segment used to implement a specific function.
Encapsulate functions in functions, which can be reused anytime and anywhere Improve
code reusability, reduce repetitive code, and improve development efficiency
1.1 Definition of function
## 函数的声明
def 函数名():
函数体
return 返回值
## 函数的调用
函数名(参数)
Function usage steps:
first define the function
and then call the function
注意:① 参数如不需要,可以省略 ② 返回值如不需要,可以省略 ③ 函数必须先定义后使用
1.2 Function parameters
When the function is running, accept the data passed in from the outside
The number of incoming parameters is unlimited.
You can use no parameters
or just use any N parameters
Precautions
Parameters in the function definition are called formal parameters
Parameters in the function call are called actual parameters The number of parameters of the function is not limited. When
commas are used to separate the incoming parameters, they must correspond to the formal parameters one by one
, separated by commas
The return value is none:
- What is None
None is a literal of type 'NoneType' used to represent: empty, meaningless - How does the function return None
without using the return statement to return None
actively return None - Use scenario
function return value
if judgment
variable definition
Case:
define a function with any name, and accept a parameter (number type, indicating body temperature)
to judge body temperature within the function (normal range: 37-38 degrees)
def check(num):
if num < 37:
print(f"体温为{
num},体温不正常,需要隔离")
elif num > 38:
print(f"体温为{
num},体温不正常,需要隔离")
else:
print(f"体温为{
num},体温正常")
check(int(input("请输入你的体温:")))
1.3 Local and global variables
Variable scope refers to the scope of variables (where variables are available and where they are not).
There are two main categories: local variables and global variables
local variable:
The so-called local variables are variables defined inside the function body, that is, they only take effect inside the function body
The role of local variables: inside the function body, temporarily save data, that is, when the function call is completed, the local variables are destroyed
Global variables:
The so-called global variable refers to the variable that can take effect inside and outside the function body.
global keyword
Use the global keyword to declare a variable as a global variable inside a function
Comprehensive case
Define a global variable: money, used to record bank card balance (default 5000000)
Define a global variable: name, used to record customer name (input when starting the program)
Define the following functions:
query balance function
deposit function
withdrawal function
main menu function
Requirements:
After the program is started, it is required to enter the customer's name.
After checking the balance, depositing, and withdrawing
, it will return to the main menu. After depositing and withdrawing, the current balance should be displayed. Note
that the number of deposits and withdrawals > 0
should be judged whether the withdrawal is greater than the balance
. If the customer chooses to quit, the program will exit, otherwise keep running
## ATM银行模拟操作
money = 5000000 # 初始金额
name = input("请输入你的名字:") # 键盘输入姓名
# 查询函数
def chax(caoz):
if caoz == True:
print("-------查询余额---------")
print(f"{
name}您好!,你当前的余额为:{
money}")
# 存款函数
def ck(num):
if num > 0:
global money # 设置money为全局变量
money += num
print(f"成功存入{
num}元")
chax(False)
# 取款函数
def qk(num):
global money # 设置money为全局变量
if num <= money: # 不能超过余额
money -= num
print(f"成功取出{
num}元")
chax(False)
# 主函数界面
def main():
print("-------------主菜单------------")
print(f"{
name},您好,欢迎来到ATM。请选择操作:")
print("查询余额\t[输入1]")
print("存款\t\t[输入2]")
print("取款\t\t[输入3]") # 通过\t制表符对齐输出
print("退出\t\t[输入4]")
return input("请输入您的选择:")
# 设置无限循环,确保程序不退出
while True:
choose_input = main() # 调用main界面
if choose_input == "1":
chax(True)
continue # 通过continue继续下一次循环,一进来就是回到了主菜单
elif choose_input == "2":
num = int(input("您想要存多少钱?请输入:"))
if num < 0:
print("输入错误")
continue
ck(num)
continue
elif choose_input == "3":
num = int(input("您想要取多少钱?请输入:"))
if num > money:
print("抱歉,余额不足")
elif num < 0:
print("输入错误")
continue
qk(num)
continue
else:
print("程序退出啦")
break # 通过break退出循环
2. Advanced functions
2.1 Function with multiple return values
Functions that have multiple return values
# 定义多返回值
def test_return()
return 1, 2 # 返回两个值
# 使用x,y接收两个值
x, y = test_return()
print(x)
print(y)
According to the order of the return value, write multiple variables in the corresponding order to receive them.
The variables are separated by commas.
Different types of data return are supported.
2.2 Multiple ways of passing parameters to functions
Different usage methods, the function has 4 common parameter usage methods:
- positional parameters
- keyword arguments
- default parameters
- variable length parameter
2.2.1 Positional parameters
definition:
Positional parameters: Pass parameters according to the parameter positions defined by the function when calling the function
grammar:
# 位置参数
def user(name, age, gender):
print(f"你的姓名是:{
name},你的年龄是:{
age},你的性别是:{
gender}")
user("小趴菜", 20, "男")
注意:传递的参数和定义的参数的顺序及个数必须一致
2.2.2 Keyword arguments
definition:
Keyword parameters: When the function is called, parameters are passed in the form of "key = value".
Function: It can make the function clearer and easier to use, and also clear the order requirements of the parameters.
grammar:
# 关键字传参
def user(name, age, gender):
print(f"你的姓名是:{
name},你的年龄是:{
age},你的性别是:{
gender}")
user(name = "小趴菜", gender = "男", age = 20) # 可变换顺序
user("小趴菜", gender = "男", age = 20) # 也可与位置参数混用
注意:函数调用时,如果有位置参数时,位置参数必须在关键字参数的前面,但关键字参数之间不存在先后顺序
2.2.3 Default parameters
definition:
Default parameters: Default parameters are also called default parameters , which are used to define functions and provide default values for parameters. When calling a function, the value of the default parameter may not be passed. Function
(注意:所有位置参数必须出现在默认参数前,包括函数定义和调用).
: When calling a function without passing parameters , the default value will be used The value corresponding to the provincial parameter.
grammar:
# 缺省参数
def user(name, age, gender = "男"):
print(f"你的姓名是:{
name},你的年龄是:{
age},你的性别是:{
gender}")
user("小趴菜", 20)
user("小趴菜", 20, "女")
注意:函数调用时,如果为缺省参数传值则修改默认参数值, 否则使用这个默认值
2.2.4 Indefinite length parameters
definition:
Indefinite-length parameters: Indefinite-length parameters are also called variable parameters. It is used in scenarios where it is uncertain how many parameters will be passed when calling (it is also possible to pass no parameters). Function: When the number of parameters is uncertain when calling a function, it can be
used variable length parameter
Types of variable-length parameters:
①position transfer
②keyword transfer
①Position transmission:
grammar:
# 不定长参数
# 位置传递 tuple类型
def user(*args):
print(args)
user("小趴菜", 20)
user("小趴菜", 20, "女")
注意:传进的所有参数都会被args变量收集,它会根据传进参数的位置合并为一个元组(tuple),args是元组类型,这就是位置传递
② Keyword transfer:
grammar:
# 关键字传递 dict类型
def user(**kwargs):
print(kwargs)
user(name = "小趴菜", age = 20)
user(name = "小趴菜", age = 20, gender = "女")
注意:参数是“键=值”形式的形式的情况下, 所有的“键=值”都会被kwargs接受, 同时会根据“键=值”组成字典.
2.3 Anonymous functions
2.3.1 Passing functions as parameters
In the previous function learning, the functions we have been using all accept data as parameters:
numbers,
strings
, dictionaries, lists, tuples, etc.
In fact , the function we learned can also be passed as a parameter into another function.
grammar:
# 函数作为参数传递
def func(compute):
result = compute(1, 2)
print(result)
def compute(x, y):
return x + y
func(compute) # 结果为3
The function compute, as a parameter, is passed into the func function for use.
func needs a function to be passed in as a parameter. This function needs to receive 2 numbers for calculation. The calculation logic is determined by the passed function. The compute function
receives 2 numbers for calculation. The compute function is passed as a parameter to the func function.
Finally, inside the func function, the compute function passed in completes the calculation of numbers,
Therefore, this is a kind of transmission of calculation logic, not data transmission.
Just like the above code, not only addition, but also any logic such as meeting, dividing, etc. can be defined by itself and passed in as a function.
2.3.2 lambda anonymous function
The def keyword in the definition of a function
can define a function with a name
. The lambda keyword can define an anonymous function (no name)
and a function with a name, which can be reused based on the name .
An anonymous function without a name that can only be used temporarily once .
Anonymous function definition syntax:
lambda 传入参数:函数体()
lambda is a keyword, which means to define an anonymous function.
The incoming parameters represent the formal parameters of the anonymous function, such as: x, y means to receive two formal parameters. The function
body is the execution logic of the function. Note: only one line can be written, and more than one can not be written line of code
def func(compute):
result = compute(1, 2)
print(result)
func(lambda x, y: x+y) # 结果为3
使用def和使用lambda,定义的函数功能完全一致,只是lambda关键字定义的函数是匿名的,无法二次使用