Zero-based learning Python|Python advanced learning day 6--function

Author Homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

3. Function realizes modular programming

In programming languages, functions are mostly used to encapsulate related codes, realize modular programming, and complete code reusable settings. Python has built-in functions and custom functions.

3.1 Function definition and call

grammar:

def functionname([parameterlist]):
   ['''comments''']
   [functionbody]

* functionname: 函数名
* parameterlist: 参数列表
* comments: 说明
* functionbody : 函数体

Example: Define a function filterchar() that filters dangerous characters

def filterchar(string):
   '''功能说明:过滤指定的字符串,并将过滤后的结果输出
      没有返回值
   '''
   import re     #导入Python的re模块
   pattern = r'(黑客)|(抓包)|(监听)|(Trojan)'   #模式字符串
   sub = re.sub(pattern,'@_@',string)   #进行模式替换
   print(sub)

Basic syntax for calling functions.

functionname([parametersvalue])

Example:

str = '我是一名热爱黑客的程序员,喜欢研究Trojan'
filterchar(str)

If you don't know what to do after defining a function, you can use pass to fill the function body, or use '...' to indicate code omission.

def functionname():
    pass
    
def functionname():
    ...

3.2 Parameter passing

The role of parameters is to pass data to the function for use, and perform corresponding data processing in the function body.

Formal parameters: Abbreviated as formal parameters, they refer to the parameters in parentheses when defining a function. Like a character in a movie script.

Actual parameter: Abbreviated as actual parameter, it refers to the actual parameter value passed when calling the function. Like an actor playing a movie role.

According to the different types of actual parameters, it is divided into value transfer (the type is an immutable type) and reference transfer (the type is a variable type). The specific difference between the two is that when passing by value, the value of the formal parameter is changed, but the value of the actual parameter remains unchanged; when passing by reference, the value of the formal parameter is changed, and the value of the actual parameter also changes.

Example:

#值传递和引用传递
def demo(obj):
    print("原值:",obj)
    obj += obj
#调用函数
print("---------值传递--------")
mot = "唯有在被追赶的时候,你才能真正的奔跑"
print("函数调用前:",mot)
demo(mot)
print("函数调用后:",mot)
print("---------引用传递--------")
list1 = ['邓肯','吉诺比利','帕克']
print("函数调用前:",list1)
demo(list1)
print("函数调用后:",list1)

When passing parameters, the quantity and data type requirements are consistent with the parameter requirements when defining functions. It can also be passed through keyword parameters, so that you don't have to keep the parameter position consistent with the definition.

for example:

functionname(height=20,width=30,height=50)

Parameter default value: You can also specify a default value for the parameter, so that you can call without passing the parameter

#函数参数默认值
def abc(str='aaa'):
    print(str)

abc()

Variable parameters: one is *parameter, the other is **parameter

*parameter : Indicates that any number of actual parameters are accepted in a tuple.

Example:

#定义可变参数
def printplayer(*name):   #定义输出我喜欢的NBA球员函数
    print('\n 我喜欢的NBA球员有:')
    for item in name:
        print(item)    #输出球员名称

printplayer('邓肯')
printplayer('邓肯','乔丹','大佛')

If you want to use an existing list as a parameter, you can add * before the name of the list

param =['邓肯','乔丹','大佛']
printplayer(*param)

**parameter: Indicates that multiple parameters that can be assigned any number of display values ​​are accepted and put into a dictionary.

#可变参数
def printsign(**sign):
    print()
    for key,value in sign.items():
        print("["+key+"] 的绰号是:"+value)

printsign(邓肯='石佛',罗宾逊='海军上将')

If you want to pass an existing dictionary as a variable parameter, you can add ** before the parameter name:

param ={'邓肯':'石佛','罗宾逊':'海军上将'}
printsign(**param)

3.3 return value

After the function is executed, the relevant execution result can be returned.

Example:

#函数返回值
def fun_checkout(name):
    nickname=""
    if name == '邓肯':
        nickname = '石佛'
    elif name == '吉诺比利':
        nickname = '妖刀'
    elif name == '罗宾随逊':
        nickname = '海军上将'
    else:
        nickname = '查无此人'
    return nickname

while FutureWarning:
    name = input("请输入NBA求员的名称:")
    nickname = fun_checkout(name)
    print("球 员:",name,"绰号:",nickname)

3.4 Scope of Variables

Local variable: refers to the variable defined inside the function, which can only be used inside the function.

Global variable: If a variable is defined outside the function, it can be used outside the function or inside the function; add the global keyword before the variable name defined in the function body, and this variable can also become a global variable.

Example:

#局部变量
def fun_variable():
    var_name = '指南针毕业设计出品'
    print(var_name)

fun_variable()
print(var_name)   #函数名使用局部变量时,抛出 NameError

Example:

#全局变量
var_name = '指南针毕业设计出品'
def fun_variable():
    print(var_name)

fun_variable()
print(var_name)

Example:

#全局变量
def fun_variable():
    global var_name
    var_name = '指南针毕业设计出品'
    print(var_name)

fun_variable()
print(var_name)

3.5 Anonymous functions

If you do not specify a name for the function, it is generally a one-time call, temporary.

result = lambda[args[,args,..argn]]:expression

* result:用于调用lambda表达式
* [arg1[,arg2,...argn]]:可选参数,用于指定要传的参数列表,多个参数间用,号分隔
* expression:必须参数,用于指定一个实现具体功能的表达式.

Example: Calculating the Radius of a Circle

import math
def circlearea(r):
   result = math.pi*r*r
   return result
r = 10
print("半径为",r,"的圆的面积为:",circlearea(r))

If you use an anonymous function to achieve the following:

import math
r = 10
result = lambda r:math.pi*r*r
print("半径为",r,"的圆的面积为:",result(r))

3.6 Python commonly used built-in functions

insert image description hereinsert image description here

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/132402700