Python入门教程 函数

程序分解方法

1:函数(function)

2:对象(obiect)

3:模块(module)

函数格式

def <name>(arg1,arg2,...agrn):
    <statements>

def hello():
    print("hello world")
    return True

hello()
>>>hello world
>>>True

向函数传入参数

def <name>(arg1,arg2,...agrn):
    <statements>

def hello(name):
    print(f"hello ,{name}")
    
hello("any")
>>>hello ,any

形参:函数定义中在内部使用地参数,在没有实际调用的时候,函数用形参来指代

实参:调用函数时由调用者传入的参数,形参指代的内容就是形参数

上述name是形参,amy是实参。参数相当于赋值。

实参类型

1:位置参数(positional argument)

2:关键字参数(keyword argument)

位置参数(两种形式)

def hello(name):
    print(f"hello,{name}")

def hello(*names):
    print(names)

hello()
hello(1)
hello(1,2)

>>>(1,2)

##*names复数 表示多个参数

关键字参数

def hello(name="world"):
    print(f"hello"{name})

hello()
>>>world
##不传输参数 则是默认的world
hello(name="a")
>>>a

**变长关键字参数

def run(a,b-1,**kwargs):
    print(kwargs)

run(1)
>>>{}
run(1,b=2)
>>>{}

run(1,c=1)
{"c"=1}
##其他的参数以字典存储

def func(a,b=0,*args,**kwargs):
##顺序必须是 常规参数,默认参数,变长元祖参数,变长关键字字典

返回值

def add(a,b):
    return a+b

add(1,2)
>>>3

def partition(string,sep):
    return string.partition(sep)

partition("/home/dongwm/bran",""/")
>>>("","/","home/dongwm/bran")

参数为函数

def hello(name):
    print(f"hello{name}")

def test(func,name = "world")
    func(name)

test(hello,"any)

hello any

本地变量(函数内申明的变量叫做本地变量)

def run(name):
    s = f"{name}"
    for x in ranges(5):
        if x == 3:
            return
    print(s)
run(text)

全局变量

g = 0
def run():
    print(g)
    g=2##局部变量
    print(g)
run()
>>>报错

global

def run():
    global g
    g += 2
    print(g)

run()
>>>2

h
>>>2

run()
>>>4

g
>>>4

##global不推荐,容易出错。定义前不要定义

作用域(scope)

B:build-in系统变量

G:global全局变量

E:enclosing嵌套作用域

L:local本地作用域

系统变量:import builtins

闭包(Closure)?:

nonlocal

匿名函数

def double(n):
    return n*2
double(10)
>>>20

f = lamda n:n*2
f(10)
>>>20

##n为函数f的参数,n*2为返回值

高阶函数-map(函数作为参数的函数) filter reduce

L1 = [1,3,6]
L2 = []

for i in 11:
    L2.append(double(i))

L2
[1,3,6]


rs = map(double,L1)
list(rs)
>>>[1,3,6]
    

https://www.learnpython.org/en/Functions
http://book.pythontips.com/en/latest/map_filter.html 3. https://docs.python.org/3/library/functools.html

猜你喜欢

转载自blog.csdn.net/weixin_42199275/article/details/81478010