Python基础教程笔记——抽象

来源:互联网 发布:kali linux手机版镜像 编辑:程序博客网 时间:2024/05/16 14:31

 

抽象

1 懒惰即美德

  1. 例子:
     1:  #Fibonacci数列函数 2:  def fibo(x): 3:      if x < 2: 4:          return; 5:      result = [0, 1] 6:      for i in range(x - 2): 7:          result.append(result[-1] + result[-2]) 8:      return result; 9:  10:  #测试11:  myarray = fibo(10)12:  print(myarray)13:  input("Press enter!")       14:  15:  #结果16:  >>> 17:  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]18:  Press enter!19:  >>> 20:  

2 抽象和结构

  1. 说明:抽象可以节省很多工作,是计算机程序让人读懂的关键;

3 创建函数

  1. 说明:
    1. 函数是可以被调用的,它执行一些操作并返回一个值,可以使用内 建函数 callable 判断函数是否可以被调用;
    2. 使用 def 语句定义函数;
    3. return 语句用来返回值;
  2. 例子:
     1:  #没有导入math模块,用callable判断函数是否可用 2:  >>> callable(math.sqrt) 3:  Traceback (most recent call last): 4:    File "<pyshell#9>", line 1, in <module> 5:      callable(math.sqrt) 6:  NameError: name 'math' is not defined 7:  #导入math模块 8:  >>> import math 9:  >>> callable(math.sqrt)10:  True11:  >>> 12:  13:  #创建函数14:  >>> def myfunc(myparam):15:          print("This is my func!")16:          return 'Finish'17:  18:  #调用函数19:  >>> myfunc('Test')20:  This is my func!21:  'Finish'22:  >>> 23:  

3.1 给函数创建文档(Documenting Function)

  1. 说明:在函数开头添加一个字符串,它会随函数一同保存,这个字符串被 称为文档字符串;
  2. 例子:
     1:  #定义函数,并在里面添加文档字符串(docstring) 2:  >>> def TestDocstring(): 3:          '这是一个文档字符串,它会随函数一同保存' 4:          print('Hello, world!') 5:          return 0 6:  #调用函数 7:  >>> TestDocstring() 8:  Hello, world! 9:  010:  #使用内置的help函数可以显示函数中的文档字符串11:  >>> help(TestDocstring)12:  Help on function TestDocstring in module __main__:13:  14:  TestDocstring()15:      这是一个文档字符串,它会随函数一同保存16:  17:  >>> 18:  

3.2 并非真正函数的函数

  1. 说明:有些函数只执行一些操作,不用向调用方返回值,这时函数定义时, 可以省略return语句;
  2. 例子:
     1:  #不含return语句的函数 2:  >>> def myfunc(): 3:          print("Hello") 4:   5:   6:  >>> myfunc() 7:  Hello 8:   9:  #含return语句的函数10:  >>> def myfunc1():11:          print("Hello")12:          return13:  14:  >>> myfunc1()15:  Hello16:  17:  >>> result = myfunc()18:  Hello19:  #result结果为空对象20:  >>> print(result)21:  None22:  >>> result = myfunc1()23:  Hello24:  #result结果为空对象25:  >>> print(result)26:  None27:  >>> 28:  

4 参数魔法

 

4.1 值从哪里来

  1. 说明:
    1. 创建函数时应该保证在收到合法参数时,执行正确的操作,收到非 法参数时,执行明显的异常(一般通过断言(assert)或者异常 (exception)来实现);
    2. 形式参数(formal parameters):在函数定义中的参数;
    3. 实际参数(actual parameters):在调用时的参数;
  2. 例子:
     1:  #name为形式参数 2:  >>> def hello(name): 3:          print("Hello, %s!" % name ) 4:   5:   6:  #'Bill'为实际参数 7:  >>> hello('Bill') 8:  Hello, Bill! 9:  >>> 10:  

4.2 能够改变参数吗

  1. 说明:在函数内为参数赋与新值不会改变外面任何变量的值;
  2. 注意:如果参数是列表,那么如果函数中修改了参数,也将修改原列表, 为了避免这种情况,可以使用分片来传递参数;
  3. 例子:
     1:  #函数不修改参数值 2:  >>> def myfunc(x): 3:          x=10 4:          return 5:   6:  >>> x = 5 7:  >>> myfunc(x) 8:  >>> x 9:  510:  >>> 11:  12:  #如果参数是列表,那么在函数中如果修改了参数,也会影响到调用的列表13:  >>> def editList(l):14:          l[0] = 'Test'15:          return16:  17:  >>> l = ['a', 'b', 'c']18:  >>> l19:  ['a', 'b', 'c']20:  >>> editList(l)21:  >>> l22:  ['Test', 'b', 'c']23:  >>> 24:  25:  #以分片的方式修改列表26:  >>> l27:  ['a', 'b', 'c']28:  >>> def editList(l):29:          l[0] = 'Test'30:          print (l)31:          return32:  33:  >>> editList(l[:])34:  ['Test', 'b', 'c']35:  >>> l36:  ['a', 'b', 'c']37:  >>> 

4.3 关键字参数和默认值

  1. 说明:
    1. 关键字参数:在调用函数时,在实参中指定实参对应的形参,这种调用 中的实参称为关键字参数;
    2. 位置参数:在调用函数时,通过位置匹配实参和形参,这种调用中的 实参称为位置参数;
  2. 注意:
    1. 关键字参数可以在函数中给参数提供默认值;
    2. 位置参数和关键字参数可以联合使用,但是应该 避免 使用这种方 式;
  3. 例子:
     1:  #关键字参数 2:  >>> def hello(greeting='Hello', name='world'): 3:          print("%s, %s" % (greeting, name)) 4:          return 5:   6:  #调用时不提供默认值,则调用后,直接使用函数定义中的默认值 7:  >>> hello() 8:  Hello, world 9:  10:  #没有指明形参名,则打印时按位置参数方式调用11:  >>> hello('Nice to meet you', 'Bill')12:  Nice to meet you, Bill13:  >>> hello('Bill', 'Hello')14:  Bill, Hello15:  16:  #使用关键字参数,调用时用关键字匹配,与位置无关17:  >>> hello(name='Bill', greeting='Nice to meet you')18:  Nice to meet you, Bill19:  >>> 20:  

4.4 收集参数

  1. 说明:
    1. 星号+参数名:参数前的星号将所有值放在同一个 元组 中,可以说 是将这些值收集起来,然后使用;
    2. 两个星号:用于处理关键字参数,可以将关键字参数收集到同一个字 典;
  2. 注意:调用时如果不提供任何元素,则收集参数就是一个空元组或空字典;
  3. 例子:
     1:  #星号+参数,将参数收集到元组中 2:  >>> def TestStar(x, *params): 3:          print(x) 4:          print(params) 5:          return 6:   7:  >>> TestStar(1, 2,3,4,5) 8:  1 9:  (2, 3, 4, 5)10:  11:  #两个星号,将参数收集到字典中12:  >>> def TestDoubleStar(x, **params):13:          print(x)14:          print(params)15:          return16:  17:  >>> TestDoubleStar(x=1,y=2,z=3)18:  119:  {'y': 2, 'z': 3}20:  >>> 21:  

4.5 函数收集逆过程

  1. 说明:将实际参数放入元组或者列表,再调用函数的过程;
  2. 注意:使用一个星号来传递元组,使用两个星号来传递字典;
  3. 例子:
     1:  #传递元组 2:  >>> def myAdd(x, y): 3:          return x+y 4:   5:  >>> data=(1231, 2131) 6:  >>> myAdd(*data) 7:  3362 8:  >>>  9:  10:  #传递字典11:  >>> def myHello(greeting, name):12:          print('%s, %s' % (greeting, name))13:          return14:  15:  >>> data={'name':'Bill Gunn', 'greeting':'Hello'}16:  >>> myHello(**data)17:  Hello, Bill Gunn18:  >>> 19:  

5 作用域

  1. 说明;在函数内声明的变量,都是局部变量,如果需要在函数内声明全局 变量,需要在声明前添加关键字 global
  2. 例子:
     1:  #局部变量 2:  >>> def TestLocalParam(): 3:          x = 10 4:          return 5:   6:  >>> x 7:  Traceback (most recent call last): 8:    File "<pyshell#4>", line 1, in <module> 9:      x10:  NameError: name 'x' is not defined11:  12:  #全局变量13:  >>> y = 1014:  >>> def TestGlobalParam():15:          global y16:          y = 10017:          return18:  >>> y19:  1020:  #使用函数修改全局变量21:  >>> TestGlobalParam()22:  >>> y23:  10024:  >>>        25:  

6 递归

 

6.1 阶乘

  1. 例子:
     1:  >>> def factorial(n): 2:          if n < 1: 3:                  return 0 4:          elif n == 1: 5:                  return 1 6:          else: 7:                  return factorial(n-1) * n 8:   9:  10:  >>> x = factorial(2)11:  >>> x12:  213:  >>> factorial(3)14:  615:  >>> factorial(4)16:  2417:  >>> for i in range(10):18:          print(factorial(i))19:  20:  21:  022:  123:  224:  625:  2426:  12027:  72028:  504029:  4032030:  36288031:  >>> 32:  

6.2 

  1. 例子:
     1:  >>> def mypow(x, y): 2:          'y must be positive integer' 3:          if y == 0: 4:                  return 1 5:          else: 6:                  return x * mypow(x, y-1) 7:   8:  >>> mypow(0, 10) 9:  010:  >>> mypow(1, 10)11:  112:  >>> mypow(2, 10)13:  102414:  >>> mypow(2, 128) * 0.000215:  6.80564733841877e+3416:  >>>       17:  

6.3 二元查找

  1. 例子:
     1:  >>> def binSearch(sequnce, number, lower, upper): 2:          if lower == upper: 3:                  assert number == sequnce[upper] 4:                  return upper 5:          middle = (lower + upper) // 2 6:          if number > sequnce[middle]: 7:                  return binSearch(sequnce, number, middle+1, upper) 8:          else: 9:                  return binSearch(sequnce, number, lower, middle)10:  11:  12:  >>> x13:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,14:  22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,15:  41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 16:  60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 17:  79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]18:  >>> binSearch(x, 10, 0, 99)19:  1020:  >>> binSearch(x, 11, 0, 99)21:  1122:  >>> 23:  

 

0 0
原创粉丝点击