小甲鱼教学笔记——函数

1. 定义函数

def MyFisrtFunction():
    print("第一个函数")
MyFisrtFunction()
第一个函数
def MySecondFunction(name):
    print(name+'我爱你')
    
MySecondFunction('余红霞')
余红霞我爱你
def add(num1,num2):
    result=num1+num2
    print(result)
add(1,3)
4

2. 函数的返回值

def add2(num1,num2):
    return(num1+num2)
    
print(add2(4,5))
9

3. 函数文档

def add3(num1,num2):
    """
    num1,num2是形参;返回相加结果
    """
    return(num1+num2)
add3.__doc__
'\n    num1,num2是形参;返回相加结果\n    '
help(add3)
Help on function add3 in module __main__:

add3(num1, num2)
    num1,num2是形参;返回相加结果
print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile:  a file-like object (stream); defaults to the current sys.stdout.\nsep:   string inserted between values, default a space.\nend:   string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

4. 关键字参数

def say(name,word):
    print(name+'->'+word)
say('余红霞','hello')
余红霞->hello
say('hello','余红霞')
hello->余红霞
say(word='hello',name='余红霞')#word、name是关键字参数
余红霞->hello

4. 默认参数

def say(name='吴亦凡',word='哈哈哈'):#默认参数
    print(name+'->'+word)
say()
吴亦凡->哈哈哈
say('余红霞','help')
余红霞->help

5. 搜集参数(可变参数)

def test(*params):
    print('参数的长度是',len(params))
    print('第二个参数是',params[1])
test(1,'余红霞',345,6,78,9)
参数的长度是 6
第二个参数是 余红霞
def test(*params,exp):
    print('参数的长度是',len(params),exp)
    print('第二个参数是',params[1])
test(1,'余红霞',345,6,78,9,exp=9)
参数的长度是 6 9
第二个参数是 余红霞
def test(*params,exp=8):
    print('参数的长度是',len(params),exp)
    print('第二个参数是',params[1])
test(1,'余红霞',345,6,78,9)
参数的长度是 6 8
第二个参数是 余红霞

6. 内嵌函数与闭包

  • 全局变量在函数里可以访问,但不要试图去修改。因为函数会创建一个同名的局部变量,而不会影响全局变量——>真想要改变:global关键字
count=5
def MyFun():
    count=10
    print(count)
MyFun()
10
print(count)
5
count=5
def MyFun():
    global count
    count=10
    print(count)
MyFun()
10
print(count)
10

6.1 内嵌函数

def Fun1():
    print("fun1()正在被调用")
    def Fun2():
        print("fun2()正在被调用")
    Fun2()
Fun1()
fun1()正在被调用
fun2()正在被调用

6.2 闭包

def FunX(x):
    def FunY(y):
        return x*y
    return FunY#FunY()构成了一个闭包
i=FunX(8)
type(i)
function
i(5)
40
FunX(8)(5)
40
def Fun1():
    x=5
    def Fun2():
        x*=x#Fun2()里的x相当于局部变量,不能修改x
        return x
    return Fun2()
Fun1()
---------------------------------------------------------------------------

UnboundLocalError                         Traceback (most recent call last)

<ipython-input-55-7499faa8d444> in <module>
----> 1 Fun1()


<ipython-input-54-7ca990c22a4f> in Fun1()
      4         x*=x
      5         return x
----> 6     return Fun2()


<ipython-input-54-7ca990c22a4f> in Fun2()
      2     x=5
      3     def Fun2():
----> 4         x*=x
      5         return x
      6     return Fun2()


UnboundLocalError: local variable 'x' referenced before assignment
def Fun1():
    x=[5]
    def Fun2():
        x[0]*=x[0]
        return x[0]
    return Fun2()
Fun1()
25
def Fun1():
    x=5
    def Fun2():
        nonlocal x
        x*=x
        return x
    return Fun2()
Fun1()
25

7. lambda表达式

  • 简洁、可以不用定义函数名
def add(x,y):
    return x+y
add(3,4)
7
g=lambda x,y:x+y
g(3,4)
7
help(filter)
Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

7.1 fliter:

  • 过滤器filter(function or None, iterable) --> filter object
  • 第一个参数如果为None或者函数,第二个参数为可迭代列表。筛选出结果为True的值
  • 第一个参数如果为None,则筛选出第二个参数的可迭代列表中为True的值
filter(None,[1,0,False,True])
<filter at 0x1f2dc38dd88>
list(filter(None,[1,0,False,True]))
[1, True]
def odd(x):
    return x%2
temp=range(10)
show=filter(odd,temp)
list(show)
[1, 3, 5, 7, 9]
list(filter(lambda x:x%2,range(10)))
[1, 3, 5, 7, 9]

7.2 map():映射

  • map(func, *iterables) --> map object
list(map(lambda x:x*2,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

8 递归

8.1 阶乘

def factorial(n):
    if n==1:
        return 1
    else:
        return n*factorial(n-1)
num=int(input('请输入一个正数:'))
result=factorial(num)
print('%d的阶乘是:%d ' % (num,result))
请输入一个正数:5
5的阶乘是:120 

8.2 斐波拉

def Fabil(n):
    if (n==1or n==2):
        return 1
    else:
        return Fabil(n-2)+Fabil(n-1)
Fabil(20)
6765
def Fabila(n):
    for i in range(n):
        if(i==0 or i==1):
            num=1
            t1=1
            t2=1
            
        else:
            num=t1+t2
            t1=t2
            t2=num
    return num
Fabila(20)
6765
def f(n):
    n1=1
    n2=1
    n3=1
    if(n==1 or n==2):
        return 1
    else:
        while (n-2)>0:
            n3=n1+n2
            n1=n2
            n2=n3
            n-=1
    return n3      
f(20)
6765

8.3 汉诺塔

def hanoi(n,a,b,c):
    if(n==1):
        print(a,"-->",c)
    else:
        hanoi(n-1,a,c,b)
        print(a,"-->",c)
        hanoi(n-1,b,a,c)       
n=int(input("请输入汉诺塔的层数:"))
hanoi(n,'A','B','C')
请输入汉诺塔的层数:3
A --> C
A --> B
C --> B
A --> C
B --> A
B --> C
A --> C

猜你喜欢

转载自blog.csdn.net/chairon/article/details/108011832
今日推荐