python if not函数_【Python】函数

定义函数

>>> def fib(n): # write Fibonacci series up to n

... """Print a Fibonacci series up to n."""

... a, b = 0, 1

... while a < n:

... print(a, end=' ')

... a, b = b, a+b

... print()

...

>>> # Now call the function we just defined:

... fib(2000)

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

第一条语句是文档字符串,要有编写这个的好习惯

变量引用会首先在局部符号表中查找,然后是外层函数的局部符号表,最后是内置名称表。

除非是 global 或者 nonlocal

没有指定返回值则返回 None

函数的其他定义形式

默认值

参数默认值在后续调用会共享

def f(a, L=[]):

L.append(a)

return L

print(f(1))

print(f(2))

print(f(3))

将输出

[1]

[1, 2]

[1, 2, 3]

任意参数列表

>>> def concat(*args, sep="/"):

... return sep.join(args)

...

>>> concat("earth", "mars", "venus")

'earth/mars/venus'

>>> concat("earth", "mars", "venus", sep=".")

'earth.mars.venus'

解包

>>> args = [3, 6]

>>> list(range(*args)) # 解包列表

[3, 4, 5]

>>> def parrot(voltage, state='a stiff', action='voom'):

... print("-- This parrot wouldn't", action, end=' ')

... print("if you put", voltage, "volts through it.", end=' ')

... print("E's", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

>>> parrot(**d) # 解包字典

-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

函数标注

函数标注是关于用户自定义函数中使用的类型的完全可选元数据信息

函数标注以字典的形式存放在函数的 annotations 属性中,并且不会影响函数的任何其他部分。

形参标注的定义方式是在形参名称后加上 : ,后面跟一个表达式

返回值标注的定义方式是加上一个组合符号 ->,后面跟一个表达式

>>> def f(ham: str, eggs: str = 'eggs') -> str:

... print("Annotations:", f.__annotations__)

... print("Arguments:", ham, eggs)

... return ham + ' and ' + eggs

...

>>> f('spam')

Annotations: {'ham': , 'return': , 'eggs': }

Arguments: spam eggs

'spam and eggs'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值