笔记-python-tutorial-4.controlflow( and function)
笔记-python-tutorial-4.controlflow( and function)
1. 函数
1.1. 定义函数
def name(x):
“””函数的第一行语句可以是可选的字符串文本,即函数的文档字符串,或docstring”””
if x>= 0:
return x
空函数
def nop():
pass
函数引用的实际参数在函数调用时引入局部符号表,实参总是传值调用
函数可返回多个值,但实际返回的是一个tuple
2、 默认参数值
def ask_ok(promt,retries=4,complaint=’yes or no.’)
3、 引用
如果函数保存到.py文件中,使用
from file_name import func_name()
来导入函数,注意文件名不包括.py
2. 函数相关
2.1. 函数参数
1.位置参数
2.default argument values:
def ask_ok(prompt, retries = 4, reminder=’Please try again!’):
注意:默认参数的值仅在编译时确认一次,此后不在修改
i = 5
def f(arg=i):
print(arg)
i = 6
f() #print 5
这在默认参数引用空表时会导致结果异常
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
This will print
[1]
[1, 2]
[1, 2, 3]
解决办法是
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
3.keyword argument:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
注意关键字参数必需跟在位置参数后面;
4.可变参数: *argv
定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(*nums)
5.unpacking argument lists
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
有点像指针,第2个函数调用时,如果不使用*,range得到的是一个数组,需要将这个数组分解为2 个参数再传递给range()。
类似的,使用**也可以解包dictionaries形式的参数。
>>> 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 !
2.2. lambda expressions
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
make返回的是一个函数,因此f是一个函数。
>>> f
<function make_incrementor.<locals>.<lambda> at 0x0000006D285F2E18>
>>> f(4)
46
尽量少这么写,写多了总会坑人的。
2.3. document strings
常用案例:
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
2.4. function 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': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'
笔记-python-tutorial-4.controlflow( and function)的更多相关文章
- Python Tutorial笔记
Python Tutorial笔记 Python入门指南 中文版及官方英文链接: Python入门指南 (3.5.2) http://www.pythondoc.com/pythontutorial3 ...
- Python Tutorial 学习(六)--Modules
6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...
- 笔记-python -asynio
笔记-python -asynio 1. 简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...
- 笔记-python lib-pymongo
笔记-python lib-pymongo 1. 开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...
- 笔记-python tutorial-9.classes
笔记-python tutorial-9.classes 1. Classes 1.1. scopes and namespaces namespace: A namespace is ...
- [译]The Python Tutorial#5. Data Structures
[译]The Python Tutorial#Data Structures 5.1 Data Structures 本章节详细介绍之前介绍过的一些内容,并且也会介绍一些新的内容. 5.1 More ...
- [译]The Python Tutorial#4. More Control Flow Tools
[译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...
- [译]The Python Tutorial#6. Modules
[译]The Python Tutorial#Modules 6. Modules 如果你从Python解释器中退出然后重新进入,之前定义的名字(函数和变量)都丢失了.因此,如果你想写长一点的程序,使 ...
- [译]The Python Tutorial#9. Classes
写在前面 本篇文章是<The Python Tutorial>(3.6.1),第九章,类的译文. 9. Classes 与其他编程语言相比,Python的类机制定义类时,最小化了新的语法和 ...
- [Notes] Learn Python2.7 From Python Tutorial
I have planed to learn Python for many times. I have started to learn Python for many times . Howeve ...
随机推荐
- 《web-Mail服务的搭建》
首先是搭建后台服务: 下载下面2个软件包 extmail-1.2.tar.gz extman-1.1.tar.gz 创建一个extsuite目录,固定格式 mkdir /var/www/extsuit ...
- webpack 安装后提示CLI
webpack 4X 后需要安装webpack-cli 请注意需要安装在同一目录 npm install --save-dev webpack -g 输入以上命令后: webpack -v 提示: T ...
- >>我要到处浪系列 之 JS随便投票小脚本
首先郑重声明:我不是对任何网站或者任何个人或组织有意见,仅仅是觉得 4点几 的评分对某些玩票的片段都太高了,为了落实想法,切实履行公民的投票权,并且 bibibabibobi biubiubiu..所 ...
- 【Linux/Ubuntu学习 11】git查看某个文件的修改历史
有时候在比对代码时,看到某些改动,但不清楚这个改动的作者和原因,也不知道对应的BUG号,也就是说无从查到这些改动的具体原因了- [注]:某个文件的改动是有限次的,而且每次代码修改的提交都会有commi ...
- 本人常用的Phpstorm快捷键
我设置的是eclipse的按键风格(按键习惯),不是phpstorm的风格 1.添加TODO(这个不是快捷键)://TODO 后面是说明,换行写实现代码 2.选择相同单词做一次性修改:Alt+J+鼠标 ...
- linux 命令——22 find (转)
find一些常用参数的一些常用实例和一些具体用法和注意事项. 1.使用name选项: 文 件名选项是find命令最常用的选项,要么单独使用该选项,要么和其他选项一起使用. 可以使用某种文件名模式来匹 ...
- Android(java)学习笔记98:如何让你的GridView不再滚动
1. 如何让你的GridView不再滚动: GridView显示不完整的原因是因为,他的外层也套用了一个滑动的控件,这个解决办法是:重写GridView,是控制GridView不能滚动,就是写一个类继 ...
- C#获取Honeywell voyager 1400g扫码后的数据
一.在类方法中加入 System.IO.Ports.SerialPort com;二.在构造方法中加入 try { com = new System.IO.Ports.SerialPort(&qu ...
- Oracle 系统表
--如果一个表拥有DBA\\ALL\\USERS三个前缀 --DBA_前缀表示DBA拥有的或者可以访问的所有关系表 --ALL_前缀表示当前用户做拥有的或者可以访问的所有关系表 --USERS-前缀表 ...
- 关于小程序button控件上下边框的显示和隐藏问题
问题: 小程序的button控件上下有一条淡灰色的边框,在空件上加上了样式 border:(none/0); 都没办法让button上下的的边框隐藏: 代码如下 <button class=&q ...