Python笔记——函数的用法

来源:互联网 发布:mac屏幕下方消失 编辑:程序博客网 时间:2024/05/26 15:55

1、判断函数是否可用:callable(f)

>>> callable(f)
False


2、改变函数参数(注意是不可变的数据结构:如 字符串、数字、元组),并不会改变外部变量值,这时函数参数只在函数内有效

def y(i):
    i=1      #调用该函数时,创建一个新的命名空间,重新创建新的一个局部变量

    return i  # return 可以没有

>>> i=10
>>> y(i)
1
>>> i
10
>>>

3、改变函数参数(注意是可变的数据结构,如:列表),可以改变外部变量的值,例如:

def y(i):
    i[0]='this is test'      #与不可变量相比,由于是可变量,指向与外部变量相同的存储空间.  此时在函数的命名空间中并没有创建变量i

>>> j=[0,1,2,3,4]        #如果不想改变可变参数的值可以,创建一个副本: i0=i[:]
>>> y(j)
>>> j
['this is test', 1, 2, 3, 4]


4、函数局部变量与全局变量的用法:调用函数时,将创建新的一个命名空间,特点:一、函数内创建的新的变量只在这个这个命名空间有效;二、可以直接调用全局变量,但如果函数内有创建相同的变量,将屏蔽全局变量,此时要想调用的话用globals()['j']这个函数

def y(i):
    i[0]='this is test'
    j="this is the local varity"
    print j
    print globals()['j']

>>> i=[0]
>>> j="global varity"
>>> y(i)
this is the local varity
global varity


5、递归:先写出递归的数学递推表达式,然后写成python语法程序:

def search(seq,num,lower=0,upper=None):
    if upper==None:
        upper=len(seq)-1
    if seq[lower]==num:
        print 'the num locate %d index in seq' % lower
    elif seq[upper]==num:
        print 'the num locate %d index in seq' % upper
    elif seq[lower]==seq[upper]:
        print 'the num is not in seq'
    elif seq[(lower+upper)/2]<num:
        return search(seq,num,(lower+upper)/2+1,upper)
    elif seq[(lower+upper)/2]>num:
        return search(seq,num,lower,(lower+upper)/2-1)
    elif seq[(lower+upper)/2]==num:
        print 'the num locate %d index in seq' % ((lower+upper)/2)

>>> x
[0, 1, 3, 5, 7, 9, 10, 10, 10, 11, 15]
>>> search(x,9)
the num locate 5 index in seq
>>> search(x,10)
the num locate 6 index in seq
>>> search(x,11)
the num locate 9 index in seq
>>> search(x,15)
the num locate 10 index in seq


6、变量命名空间实例

以下是一个示例,演示了如何引用不同作用域和命名空间,以及 global 和 nonlocal 如何影响变量绑定: 
def scope_test():     def do_local(): 
        spam = "local spam"     def do_nonlocal():         nonlocal spam 
        spam = "nonlocal spam"     def do_global():         global spam 
        spam = "global spam"  
    spam = "test spam"     do_local() 
    print("After local assignment:", spam)     do_nonlocal() 
    print("After nonlocal assignment:", spam)     do_global() 
    print("After global assignment:", spam)  
scope_test() 
print("In global scope:", spam) 
以上示例代码的输出为: 
After local assignment: test spam 
After nonlocal assignment: nonlocal spam 

After global assignment: nonlocal spam 

In global scope: global spam 
注意: local 赋值语句是无法改变 scope_test 的 spam 绑定。 nonlocal 赋值语句改变了 scope_test 的spam 绑定,并且 global 赋值语句从模块级改变了 spam 绑定。 你也可以看到在 global 赋值语句之前对 spam 是没有预先绑定的。




0 0
原创粉丝点击