函数:程序个体中的代码块(优点:可以降低代码量/维护成本,使程序更容易阅读)

def dec2bin(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 2)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])

 

函数的参数:def/add/result,应该尽量精简

形参()里的x

def MyFun(x):
    return x ** 3

y = 3
print(MyFun(y))

实参:递入的具体值

>>> def MyFirstFunction(name):
    '函数定义过程中的name是叫形参'
    #因为Ta只是一个形式,表示占据一个参数位置
    print('传递进来的' + name + '叫做实参,因为Ta是具体的参数值!')

>>> MyFirstFunction('小甲鱼')
传递进来的小甲鱼叫做实参,因为Ta是具体的参数值!

关键字参数Create

def SaySome(name,words):
    print(name+'->'+words)
    
>>> SaySome('小甲鱼','让编程改变世界')
小甲鱼->让编程改变世界
>>> SaySome('让编程改变世界','小甲鱼')
让编程改变世界->小甲鱼
>>> SaySome(words='让编程改变世界',name='小甲鱼')
小甲鱼->让编程改变世界

默认函数

>>> def SaySome(words='让编程改变世界',name='小甲鱼'):
    print(name+'->'+words)

>>> SaySome()
小甲鱼->让编程改变世界
>>> SaySome('苍井空')
小甲鱼->苍井空
>>> SaySome(name=苍井空)
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    SaySome(name=苍井空)
NameError: name '苍井空' is not defined
>>> SaySome(name='苍井空')
苍井空->让编程改变世界

收集(可变)参数

def test(*params):
    print('参数的长度是:',len(params))
    print('第二个参数是:',params[1])
    
>>> test(1,'小甲鱼'3.14,)
SyntaxError: invalid character in identifier
>>> test(1,'小甲鱼',3.14,5,6,7)
参数的长度是: 6
第二个参数是: 小甲鱼
def test(*params,exp=8):
        print('参数的长度是:',len(params),exp);
        print('第二个参数是:',params[1]);
        
>>> test(1,'小甲鱼',3.14,5,6,7,8,exp)
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    test(1,'小甲鱼',3.14,5,6,7,8,exp)
NameError: name 'exp' is not defined
>>> test(1,'小甲鱼',3.14,5,6,7,8,exp=8)
参数的长度是: 7 8
第二个参数是: 小甲鱼

函数的返回值:return/返回定义值

def gcd(x,y):
    while y:
        t=x%y
        x=y
        y=t
    return x

 函数与过程的区别(函数一定要有结果,过程没有结果)

def hello():
    print('Hello,World!')
    
>>> temp=hello()
Hello,World!
>>> temp
>>> print(temp)
None
>>> type(temp)
<class 'NoneType'>
def back():
    return[1,3.14,'小甲鱼']

>>> back
<function back at 0x000001D67BB98F28>
>>> back()
[1, 3.14, '小甲鱼']
def back():
    return 1,3.14,'小甲鱼'

>>> back()
(1, 3.14, '小甲鱼')

变量的作用域:局部变量和全局变量

def discounts(price, rate):
    final_price = price * rate      #final_price是局部变量
    return final_price

old_price = float(input('请输入原价:'))
rate = float(input('请输入折扣率:'))
new_price = discounts(old_price, rate)
print('打折后价格是:', new_price)
var = ' Hi '

def fun1():
    global var
    var = ' Baby '
    return fun2(var)

def fun2(var):
    var += 'I love you'
    fun3(var)
    return var

def fun3(var):
    var = ' 小甲鱼 '

print(fun1())
def MyFun():
    global count
    count=-10
    print(10)

>>> MyFun()
10
>>> print(count)
-10

内嵌(内部)函数

def outside():
    print('I am outside')
    def inside():
        print('I am inside')

>>> inside()                   #内嵌函数无法在函数外进行调用
Traceback (most recent call last):
  File "<pyshell#234>", line 1, in <module>
    inside()
NameError: name 'inside' is not defined
>>> outside()
I am outside
def fun1():
    print('fun1()正在被调用')
    def fun2():
        print('fun2()正在被调用')
    fun2()

    
>>> fun1()
fun1()正在被调用
fun2()正在被调用

>>> fun2()
Traceback (most recent call last):
File "<pyshell#202>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined

 闭包(closure)

def funOut():
    def funIn():
        print('宾果!你成功访问到我啦!')
    return funIn()
funOut()
>>> def FunX(x):
      def FunY(y):
          return x*y
      return FunY

>>> i=FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x000001D67BBD06A8>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>> FunY(5)
Traceback (most recent call last):
  File "<pyshell#212>", line 1, in <module>
    FunY(5)
NameError: name 'FunY' is not defined
def Fun1():
    x=5
    def Fun2():
        x*=x
        return x
    return Fun2

>>> Fun1()
<function Fun1.<locals>.Fun2 at 0x000001D67BBD08C8>
>>> def Fun1():
    x=5
    def Fun2():
        x*=x
        return x
    return Fun2()

>>> Fun1()
Traceback (most recent call last):
  File "<pyshell#218>", line 1, in <module>
    Fun1()
  File "<pyshell#217>", line 6, in Fun1
    return Fun2()
  File "<pyshell#217>", line 4, in Fun2
    x*=x
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  #Python3的进一步改进
        x*=x
        return x
    return Fun2()

>>> Fun1()
25
def outside():
     var = 5
     def inside():
         var = 3
         print(var)
     inside()
outside()

def outside():
     var = 5
     def inside():
         nonlocal var
         print(var)
         var = 8
     inside()
outside()

 匿名函数lambda

def ds(x):
    return 2*x+1
>>> ds(5)
11
>>> lambda x:2*x+1
<function <lambda> at 0x000001D67BBE2048>
>>> g=lambda x:2*x+1
>>> g(5)
11

def add(x,y):
    return x+y
>>> add(3,4)
7
>>> lambda x,y:x+y
<function <lambda> at 0x000001D67BBE2268>
>>> g=lambda x,y:x+y
>>> g(3,4)
7

.

两个牛逼常用的函数filter()过滤无用/不用信息和map()映射

filter(None,[1,0,False,True])
<filter object at 0x000001D67BBD9BA8>
>>> 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]
list(map (lambda x:x*2,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
def is_odd(x):
        if x % 2:
                return x
        else:
                return None

>>> is_odd(0)
>>> is_odd(101)
101
>>> lambda x : x if x % 2 else None
<function <lambda> at 0x000001D67BBE26A8>
>>> y=lambda x : x if x % 2 else None
>>> y(100)
>>> y(101)
101

 

搞清下面的概念,异同:序列/列表/元组/字符串/循环函数

 

模块

对象

def funOut():

    def funIn():

        print('宾果!你成功访问到我啦!')

    return funIn()

posted on 2018-01-04 13:49  Samyll  阅读(210)  评论(0编辑  收藏  举报