流控语句
选择语句
关键字:if elif else 可以用 switch case 替代
循环
for 可以遍历列表
如:for w in words:
print(w, len(w))
内置函数 range 可以返回一个数字序列 ,例如 :range(3,5) 输出:3,4
break continue
注意了,下面这个语法比较奇葩
for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
for 后面跟着一个 else,代表循环执行完再执行else ,类似的 try 也有else 语句
pass 什么也不做,给我留下了巨大的想象空间啊
函数
特别之处: 可以没有return 函数名可以赋值给另外一个变量,实现函数的别名
形式参数可以有默认值
这个例子有点颠覆认知:
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 parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
调用方式:
parrot(voltage=1000)
下面这个例子比较复杂: * 代表列表, ** 代表字典
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
它可以像这样调用:
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
当然它会打印:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
任意参数列表
话不多说,上代码:
>>> def concat(*args, sep="/"):
... return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
'''
解压缩参数列表
列表解压缩:
>>> 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]
字典解压缩:
>> 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 !
Lambad 表达式
示例一:返回一个函数
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
示例二:传递一个函数
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
注意:说说我的理解,sort函数按key自定义排序一直搞不清楚有什么用,复杂又难懂,照着这个例子来说
lambda pair: pair[1] pair 是元组,pair[1]是元组中第二个元素,所以整体的意思是按元组中的第二个元素进行排序
文档字符串
示例如下:
>>> 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.
功能注释 语法比较奇葩,不能忍
示例如下:
>>> 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'
编码风格: PEP8标准
使用4个空格缩进
换行
使用docstrings
vscode 配置技巧:
ctrl+p 输入如下命令
ext install python #安装 python 插件
F5 运行,调试
配置flake8 # 静态代码检查工具
打开命令行
输入 "pip install flake8"
安装flake8成功后,打开VScode,文件->首选项->用户设置,在settings.json文件中输入"python.linting.flake8Enabled": true
配置yapf
安装yapf之后在VScode中按Ctrl+Shift+I即可自动格式化代码
打开命令行
输入 "pip install yapf"
安装yapf成功后,打开VScode,文件->首选项->用户设置,在settings.json文件中输入"python.formatting.provider": "yapf"
安装 Rope 重构库 配合 vscode 可以实现按F2 重命名变量
查看函数或者类的定义
Ctrl+鼠标左键点击函数名或者类名即可跳转到定义处,在函数名或者类名上按F12也可以实现同样功能