4 道练习题·预计 145 分钟·做对一题解锁下一段
本来不应该把这个章节放在那面前面的,因为还没进行学习之前,直接看这个章节,会感觉有很多莫名其妙的东西。
但是把这个章节放在前面的用意,只是让大家预览一下,有个印象,而且在以后的学习中,也方便大家查阅。
#-*-coding:utf-8-*-标识每行代码尽量不超过 80 个字符(在特殊情况下可以略微超过 80 ,但最长不得超过 120)
理由:
简单说,自然语言使用双引号,机器标示使用单引号,因此 代码里 多数应该使用 单引号
"..."u"你好世界"'...'
例如 dict 里的 keyr"...""""......"""class A:
def __init__(self):
pass
def hello(self):
pass
def main():
pass # 正确的写法
import os
import sys
# 不推荐的写法
import sys,os
# 正确的写法
from subprocess import Popen, PIPE# 正确的写法
from foo.bar import Bar
# 不推荐的写法
from ..bar import Barimport os
import sys
import msgpack
import zmq
import foofrom myclass import MyClassimport bar
import foo.bar
bar.Bar()
foo.bar.Bar()[=,-,+=,==,>,in,is not, and]:# 正确的写法
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# 不推荐的写法
i=i+1
submitted +=1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b),之后要有空格# 正确的写法
def complex(real, imag):
pass
# 不推荐的写法
def complex(real,imag):
pass# 正确的写法
def complex(real, imag=0.0):
pass
# 不推荐的写法
def complex(real, imag = 0.0):
pass# 正确的写法
spam(ham[1], {eggs: 2})
# 不推荐的写法
spam( ham[1], { eggs : 2 } )# 正确的写法
dict['key'] = list[index]
# 不推荐的写法
dict ['key'] = list [index]# 正确的写法
x = 1
y = 2
long_variable = 3
# 不推荐的写法
x = 1
y = 2
long_variable = 3Python 支持括号内的换行。这时有两种情况。
foo = long_function_name(var_one, var_two,
var_three, var_four)def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)使用反斜杠\换行,二元运算符+ .等应出现在行末;长字符串也可以用此法换行
session.query(MyTable).\
filter_by(id=1).\
one()
print 'Hello, '\
'%s %s!' %\
('Harry', 'Potter')禁止复合语句,即一行中包含多个语句:
# 正确的写法
do_first()
do_second()
do_third()
# 不推荐的写法
do_first();do_second();do_third();if/for/while一定要换行:
# 正确的写法
if foo == 'blah':
do_blah_thing()
# 不推荐的写法
if foo == 'blah': do_blash_thing()docstring 的规范中最其本的两点:
"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""
"""Oneline docstring"""“#”号后空一格,段落件用空行分开(同样需要“#”号)
# 块注释
# 块注释
#
# 块注释
# 块注释至少使用两个空格和语句分开,注意不要使用无意义的注释
# 正确的写法
x = x + 1 # 边框加粗一个像素
# 不推荐的写法(无意义的注释)
x = x + 1 # x加1在代码的关键部分(或比较复杂的地方), 能写注释的要尽量写注释
比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性
app = create_app(name, options)
# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================
if __name__ == '__main__':
app.run()作为文档的Docstring一般出现在模块头部、函数和类的头部,这样在python中可以通过对象的__doc__对象获取文档. 编辑器和IDE也可以根据Docstring给出自动提示.
# -*- coding: utf-8 -*-
"""Example docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""# 不推荐的写法(不要写函数原型等废话)
def function(a, b):
"""function(a, b) -> list"""
... ...
# 正确的写法
def function(a, b):
"""计算并返回a到b范围内数据的平均值"""
... ...def func(arg1, arg2):
"""在这里写函数的一句话总结(如: 计算平均值).
这里是具体描述.
参数
----------
arg1 : int
arg1的具体描述
arg2 : int
arg2的具体描述
返回值
-------
int
返回值的具体描述
参看
--------
otherfunc : 其它关联函数等...
示例
--------
示例使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""文档注释不限于中英文, 但不要中英文混用
文档注释不是越长越好, 通常一两句话能把情况说清楚即可
模块、公有类、公有方法, 能写文档注释的, 应该尽量写文档注释
# 正确的模块名
import decoder
import html_parser
# 不推荐的模块名
import Decoderclass Farm():
pass
class AnimalFarm(Farm):
pass
class _PrivateFarm(Farm):
passdef run():
pass
def run_with_env():
passclass Person():
def _private_func():
passif __name__ == '__main__':
count = 0
school_name = ''MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600MAX_OVERFLOW = 100
class FooBar:
def foo_bar(self, print_):
print(print_)
来看下面这段「校验登录」的代码:
def login(user, password):
if user is not None:
if user.is_active:
if user.check_password(password):
if not user.is_locked:
return '登录成功'
else:
return '账户已锁定'
else:
return '密码错误'
else:
return '账户未激活'
else:
return '用户不存在'四层嵌套——读到第三层 if 时,你已经记不清第一层的条件是什么了。
「先处理边界情况,主流程才能放在最外层」——这就是早返回的核心思想。
def login(user, password):
if user is None:
return '用户不存在'
if not user.is_active:
return '账户未激活'
if not user.check_password(password):
return '密码错误'
if user.is_locked:
return '账户已锁定'
return '登录成功'变化看出来了吗?
else凡是看到这种结构:
if 条件成立:
# 主流程一大段
...
else:
return 错误都可以改写成:
if not 条件成立:
return 错误
# 主流程一大段(无缩进)
...主流程从 1 层缩进退回到 0 层。多个条件叠加时效果尤为明显。
不是所有 if 都该早返回。如果两个分支地位平等——比如「奇数返回 X、偶数返回 Y」——那就老老实实写 if/else,没必要硬塞进早返回。
def parity(n):
if n % 2 == 0:
return '偶数'
else:
return '奇数'这样反而清楚。早返回是为了摊平错误处理,不是为了消灭所有 else。
下面这段函数 check(score) 用了三层嵌套——请用早返回重写一个函数 check(score),逻辑保持一致:
score < 0 或 score > 100:返回 '非法分数'score >= 90:返回 '优秀'score >= 60:返回 '及格''不及格'然后依次调用 print(check(95))、print(check(72))、print(check(40))、print(check(150))。
输出应该是:
优秀
及格
不及格
非法分数提示:「早返回」就是先把异常情况 return 掉,把主流程留在最外层,不写 else、不嵌套。
推荐一个,全网最全最友好的中文 AI 编程指南: coding.stormzhang.ai