Functions in Python (definition, call, formal parameter, actual parameter, required parameter, default parameter, variable parameter, keyword parameter)

1. Definition and call of
function 1. Define function

#定义最大值函数
def max_num(x:int,y:int)->int:    #此处的x、y为形参      
   #调用函数函数名(形参),调用函数时的参数,实参。一般实参要和形参一一对应  
   #形参是形式参数,可以任意更改
   max = x if x > y else y   
   return max
#print(help(max_num))

#创建一个空函数
def login(username,password):
   pass

2. Call function

result = max_num(10,20)    #此处的10,20为实参
print(result)

Insert picture description here

2. Required parameters and default parameters

  1. Required parameters: parameters that must be passed
    2) Default parameters: formal parameters and actual parameters can be different. If no parameters are passed, use the default value, if passed parameters, use the
    passed parameters
def sum_num(num1,num2=19):   #此处形参有两个,实参仅有一个,但num2传递了19
   sum=num1+num2
   return sum

result = sum_num(11)         #此处执行result= 11 + 19
print(result)

Insert picture description here

3. Variable parameters
Variable parameters (pass multiple values ​​at the same time, only need to use one parameter args to define, under normal circumstances *args data is stored in a tuple of tuples)

def sum_num(*args):
   print("args:",args)
   print("args type: ",type(args))
   return sum(args)
result = sum_num(12,18,9,7,6)
print(result)

Insert picture description here

4. Keyword parameters
Keyword parameters: The number of parameters passed by the user can be multiple and each parameter requires two pieces of information (key-value).
Generally, **kwargs is used to indicate that the data is stored as a dict

def enroll(name,**kwargs):
   print(name)
   print(kwargs)
enroll("westos",age=10,city="xian")   

Insert picture description here

Exercise 1
Find the factorial of a number
Insert picture description here
Exercise 2
Bubble sort algorithm
Bubble sort repeatedly visits the list of elements that need to be sorted, compares two adjacent elements in turn, and exchanges if the order (such as from largest to smallest or from smallest to largest) is wrong Their location. Repeat until no adjacent elements need to be exchanged, then the element list sorting is completed.
Insert picture description here
Exercise 3
Quick Sort
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42958401/article/details/108858552