python——函数

函数

python也分形参实参

函数文档(突然发现tab是好用的)

 def myfirstfun(name):

'xxxx'

#xxxxx

print(name)

>>> myfirstfun(x)

   

SyntaxError: invalid character in identifier

>>> myfirstfun('x')

x

>>> myfirstfun.__doc__

'xxxx'

>>> help(myfirstfun)

Help on function myfirstfun in module __main__:

myfirstfun(name)

    xxxx

>>> 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.



>>> 

关键字参数

>>> tell('misszhou','让编程编织梦想')

misszhou让编程编织梦想

>>> tell(wors='words',name='misszhou')

Traceback (most recent call last):

  File "<pyshell#16>", line 1, in <module>

    tell(wors='words',name='misszhou')

TypeError: tell() got an unexpected keyword argument 'wors'

>>> tell(words='words',name='misszhou')

misszhouwords


默认参数

>>> def saysome(name='name',word='word'):

print(name+word)

>>> saysome

<function saysome at 0x000000A74A7969D8>

>>> saysome()

nameword


收集参数(这玩意别的语言没有,类C语言有可变参数啊)print的实现

>>> def test(*par):

print('len',len(par))

print(par[0])

>>> test(1,2,3,4)

len 4

1

>>> def test(*par,exp=8)

SyntaxError: invalid syntax

>>> def test(*par,exp=8):

print('len:',len(par),exp)

print('第二个参数为',par[1])

>>> test(1,2,3,4)

len: 4 8


第二个参数为 2

函数与过程

python可以返回多个值(通过列表打包呗)

>>> def back():

return 1,'misszhou'

>>> back()

(1, 'misszhou')


python也分全局变量/局部变量

一段神奇的代码

def discount(price,rate):

    fin_price=price*rate

    # print('这里试图打印全局变量old_price:',old_price)

    old_price=50

    print('1修改后oldprice的值',old_price)

    return fin_price

old_price=float(input('请输入原价:'))

rate=float(input('请输入折扣;'))

new_price=discount(old_price,rate)

print('2修改后oldprice的值',old_price)

print('折扣后价格:',new_price)

请输入原价:100

请输入折扣;0.9

1修改后oldprice的值 50

2修改后oldprice的值 100.0

折扣后价格: 90.0


为什么呢?在函数里面的那个是新创建的局部变量!!不是原来的那个全局变量

我要是想在函数里面修改全局变量,也可以嵌套定义

内嵌函数和闭包

global关键字(这玩意和php一样啊=w=

>>> count=5

>>> def myfun()

SyntaxError: invalid syntax

>>> def myfun():

count=10

print(count)

>>> def myfun()

SyntaxError: invalid syntax

>>> myfun()

10

>>> print(count)

5

>>> def myfun():

global count

count=10

print(10)

      

SyntaxError: invalid character in identifier

>>> def myfun():

global count

count=10

print(10)

>>> def myfun():

global count

count=10

print(count)

>>> def myfun()

SyntaxError: invalid syntax

>>> myfun()

10

>>> print(count)

10


函数嵌套

>>> def fun1():

print('fun1')

def fun2():

print('fun2')

fun2()

>>> fun1()

fun1

fun2

>>> fun2()

Traceback (most recent call last):

  File "<pyshell#68>", line 1, in <module>

    fun2()

NameError: name 'fun2' is not defined

>>> fun1().fun2()

fun1

fun2

Traceback (most recent call last):

  File "<pyshell#69>", line 1, in <module>

    fun1().fun2()

AttributeError: 'NoneType' object has no attribute 'fun2'

闭包(这玩意js有啊)

>>> def funx(x):

def funy(y):

return x*y

return funy

>>> i=funx(8)

>>> i

<function funx.<locals>.funy at 0x0000004A51346A60>

>>> type(i)

<class 'function'>

>>> i(5)

40

>>> funx(4)(4)

16

>>> funy(8)

Traceback (most recent call last):

  File "<pyshell#80>", line 1, in <module>

    funy(8)

NameError: name 'funy' is not defined

>>> def fun1():

x=5

def fun2():

x*=x

return x

return fun2()

>>> fun1()

Traceback (most recent call last):

  File "<pyshell#88>", line 1, in <module>

    fun1()

  File "<pyshell#87>", line 6, in fun1

    return fun2()

  File "<pyshell#87>", line 4, in fun2

    x*=x

UnboundLocalError: local variable 'x' referenced before assignment

>>> def fun1():

x[0]=5

def fun2():

x[0]*=x[0]

return x[0]

return fun2()

>>> fun1()

Traceback (most recent call last):

  File "<pyshell#91>", line 1, in <module>

    fun1()

  File "<pyshell#90>", line 2, in fun1

    x[0]=5

NameError: name 'x' is not defined

>>> 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


lambda表达式

参数:返回值

>>> x=lambda x,y:x+y

>>> print(x)

<function <lambda> at 0x0000004A51346EA0>

>>> x(3,4)

7


这玩意在js里面不也有么……

lambda表达式的作用

省下定义函数的作用、不需要考虑函数名、省得函数阅读跳到开头定义部分

filter()过滤器

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).

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  

 |  __next__(self, /)

 |      Implement next(self).

 |  

 |  __reduce__(...)<pre name="code" class="python">>>> def odd(x):

return x%2

>>> temp=range(10)

>>> show=filter(odd,temp)

>>> list(show)

[1, 3, 5, 7, 9]

| Return state information for pickling.filter(None,[1,0,False,True])<filter object at 0x0000004A5135B240>>>> 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)))


map()

映射

list(map(lambda x:x%2,range(10)))

[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]


递归

可以人为规定递归层数

import sys

sys.setrecursionlimit(10000)


输出阶乘

def func(num):

    if(num==1):

        return 1

    return num*func(num-1)

num=int(input())

print(func(num))


递归的斐波那契

def fun(n):

    if(n==3):

        return 2

    elif(n==2):

        return 1

    return fun(n-1)+fun(n-2)

print(fun(12))


汉诺塔

def hano(n,x,y,z):

    if(n==1):

        print(x,"-->",z)

        return

    hano(n-1,x,z,y)

    print(x,"-->",z)

    hano(n-1,y,x,z)

n=int(input())

hano(n,'x','y','z')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前言 本书的读者 本书的由来 本书目前的状况 官方网站 约定条款 欢迎给我反馈 值得思考的一些东西 1. 介绍 简介 Python的特色 概括 为什么不使用Perl? 程序员的话 2. 安装Python Linux和BSD用户 Windows®用户 概括 3. 最初的步骤 简介 使用带提示符的解释器 挑选一个编辑器 使用源文件 输出 它如何工作 可执行的Python程序 获取帮助 概括 4. 基本概念 字面意义上的常量 数 字符串 变量 标识符的命名 数据类型 对象 输出 它如何工作 逻辑行与物理行 缩进 概括 5. 运算符与表达式 简介 运算符 运算符优先级 计算顺序 结合规律 表达式 使用表达式 概括 6. 控制流 简介 if语句 使用if语句 它如何工作 while语句 使用while语句 for循环 使用for语句 break语句 使用break语句 continue语句 使用continue语句 概括 7. 函数 简介 定义函数 函数形参 使用函数形参 局部变量 使用局部变量 使用global语句 默认参数值 使用默认参数值 关键参数 使用关键参数 return语句 使用字面意义上的语句 DocStrings 使用DocStrings 概括 8. 模块 简介 使用sys模块 字节编译的.pyc文件 from..import语句 模块的__name__ 使用模块的__name__ 制造你自己的模块 创建你自己的模块 from..import dir()函数 使用dir函数 概括 9. 数据结构 简介 列表 对象与类的快速入门 使用列表 元组 使用元组 元组与打印语句 字典 使用字典 序列 使用序列 参考 对象与参考 更多字符串的内容 字符串的方法 概括 10. 解决问题——编写一个Python脚本 问题 解决方案 版本一 版本二 版本三 版本四 进一步优化 软件开发过程 概括 11. 面向对象的编程 简介 self 类 创建一个类 对象的方法 使用对象的方法 __init__方法 使用__init__方法 类与对象的变量 使用类与对象的变量 继承 使用继承 概括 12. 输入/输出 文件 使用文件 储存器 储存与取储存 概括 13. 异常 错误 try..except 处理异常 引发异常 如何引发异常 try..finally 使用finally 概括 14. Python标准库 简介 sys模块 命令行参数 更多sys的内容 os模块 概括 15. 更多Python的内容 特殊的方法 单语句块 列表综合 使用列表综合 在函数中接收元组和列表 lambda形式 使用lambda形式 exec和eval语句 assert语句 repr函数 概括 16. 接下来学习什么? 图形软件 GUI工具概括 探索更多内容 概括 A. 自由/开放源码软件(FLOSS) B. 关于本书 后记 关于作者 关于译者 关于简体中文译本 C. 修订记录 时间表 术语表 表格5.1 运算符与它们的用法 5.2 运算符优先级 15.1 一些特殊的方法 例子3.1 使用带提示符的Python解释器 3.2 使用源文件 4.1 使用变量和字面意义上的常量 5.1 使用表达式 6.1 使用if语句 6.2 使用while语句 6.3 使用for语句 6.4 使用break语句 6.5 使用continue语句 7.1 定义函数 7.2 使用函数形参 7.3 使用局部变量 7.4 使用global语句 7.5 使用默认参数值 7.6 使用关键参数 7.7 使用字面意义上的语句 7.8 使用DocStrings 8.1 使用sys模块 8.2 使用模块的__name__ 8.3 如何创建你自己的模块 8.4 使用dir函数 9.1 使用列表 9.2 使用元组 9.3 使用元组输出 9.4 使用字典 9.5 使用序列 9.6 对象与参考 10.1 备份脚本——版本一 10.2 备份脚本——版本二 10.3 备份脚本——版本三(不工作!) 10.4 备份脚本——版本四 11.1 创建一个类 11.2 使用对象的方法 11.3 使用__init__方法 11.4 使用类与对象的变量 11.5 使用继承 12.1 使用文件 12.2 储存与取储存 13.1 处理异常 13.2 如何引发异常 14.1 使用sys.argv 15.1 使用列表综合 15.2 使用lambda形式

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值