习题 37: 复习各种符号

阅读原文

现在该复习你学过的符号和 python 关键字了,而且你在本节还会学到一些新的 东西。我在这里所作的是将所有的 Python 符号和关键字列出来,这些都是值得 掌握的重点。

在这节课中,你需要复习每一个关键字,从记忆中想起它的作用并且写下来, 接着上网搜索它真正的功能。有些内容可能是无法搜索的,所以这对你可能有些 难度,不过你还是需要坚持尝试。

如果你发现记忆中的内容有误,就在索引卡片上写下正确的定义,试着将自己的 记忆纠正过来。如果你就是不知道它的定义,就把它也直接写下来,以后再做研究。

最后,将每一种符号和关键字用在程序里,你可以用一个小程序来做,也可以尽量 多谢一些程序来巩固记忆。这里的关键点是明白各个符号的作用,确认自己没搞错, 如果搞错了就纠正过来,然后将其用在程序里,并且通过这样的方式巩固自己的 记忆。

Keywords(关键字)

Keyword Description Example
and Logical and. True and False == False
as Part of the with-as statement. with X as Y: pass
assert Assert (ensure) that something is true. assert False, "Error!"
break Stop this loop right now. while True: break
class Define a class. class Person(object)
continue Don't process more of the loop, do it again. while True: continue
def Define a function. def X(): pass
del Delete from dictionary. del X[Y]
elif Else if condition. if: X; elif: Y; else: J
else Else condition. if: X; elif: Y; else: J
except If an exception happens, do this. except ValueError, e: print e
exec Run a string as Python. exec 'print "hello"'
finally Exceptions or not, finally do this no matter what. finally: pass
for Loop over a collection of things. for X in Y: pass
from Importing specific parts of a module. from x import Y
global Declare that you want a global variable. global X
if If condition. if: X; elif: Y; else: J
import Import a module into this one to use. import os
in Part of for-loops. Also a test of X in Y. for X in Y: pass also 1 in [1] == True
is Like == to test equality. 1 is 1 == True
lambda Create a short anonymous function. s = lambda y: y ** y; s(3)
not Logical not. not True == False
or Logical or. True or False == True
pass This block is empty. def empty(): pass
print Print this string. print 'this string'
raise Raise an exception when things go wrong. raise ValueError("No")
return Exit the function with a return value. def X(): return Y
try Try this block, and if exception, go to except. try: pass
while While loop. while X: pass
with With an expression as a variable do. with X as Y: pass
yield Pause here and return to caller. def X(): yield Y; X().next()
KEYWORD DESCRIPTION EXAMPLE
and 逻辑与 True and False == False
as with-as语句的一部分 with X as Y: pass
assert 声明 assert False, "Error!"
break 停止整个循环 while True: break
class 定义一个类 class Person(object)
continue 停止这一次循环,但继续下一次循环 while True: continuev
def 定义一个函数 def X(): pass
del 从字典中删除 del X[Y]
elif Else if 条件 if: X; elif: Y; else: J
else Else 条件 if: X; elif: Y; else: J
except 如果捕获异常,执行该代码块 except ValueError, e: print e
exec 将字符串作为Python代码执行 exec 'print "hello"'
finally 不管是否有异常,finally代码块都执行 finally: pass
for for循环 for X in Y: pass
from 从某一模块中引入特定部分 import X from Y
global 定义一个全局变量 global X
if If 条件 if: X; elif: Y; else: J
import 引入一个模块到当前模块 import os
in for循环的一部分/ 测试X in Y. for X in Y: pass / 1 in [1] == True
is 类似==,判断相等 1 is 1 == True
lambda 创建一个无名函数 s = lambda y: y ** y; s(3)
not 逻辑非 not True == False
or 逻辑或 True or False == True
pass 该代码块为空 def empty(): pass
print 打印一个字符串 print 'this string'
raise 代码出错时,抛出一个异常 raise ValueError("No")
return 退出函数并返回一个返回值 def X(): return Y
try 尝试代签代码块,有异常则进入except代码块 try: pass
while While循环 while X: pass
with 一个变量的别名 with X as Y: pass
yield 暂停, 返回给调用者 def X(): yield Y; X().next()

数据类型

针对每一种数据类型,都举出一些例子来,例如针对 string,你可以举出一些字符串, 针对 number,你可以举出一些数字。

Type Description Example
True True boolean value. True or False == True
False False boolean value. False and True == False
None Represents "nothing" or "no value". x = None
strings Stores textual information. x = "hello"
numbers Stores integers. i = 100
floats Stores decimals. i = 10.389
lists Stores a list of things. j = [1,2,3,4]
dicts Stores a key=value mapping of things. e = {'x': 1, 'y': 2}
TYPE DESCRIPTION EXAMPLE
True True 布尔值. True or False == True
False False 布尔值. False and True == False
None 表示 "nothing" 或者"no value". x = None
strings 字符串,储存文本信息 x = "hello"
numbers 储存整数 i = 100
floats 储存小数 i = 10.389
lists 储存某种东西的列表 j = [1,2,3,4]
dicts 储存某些东西的键值对 e = {'x': 1, 'y': 2}

字符串转义序列(Escape Sequences)

对于字符串转义序列,你需要再字符串中应用它们,确认自己清楚地知道它们的功能。

Escape Description
\\ Backslash
\' Single-quote
\" Double-quote
\a Bell
\b Backspace
\f Formfeed
\n Newline
\r Carriage
\t Tab
\v Vertical tab
ESCAPE DESCRIPTION
\\ 斜线
\' 单引号
\" 双引号
\a Bell
\b 退格
\f Formfeed
\n 换行
\r Carriage
\t Tab键
\v 垂直的tab

字符串格式化(String Formats)

一样的,在字符串中使用它们,确认它们的功能。

Escape Description Example
%d Decimal integers (not floating point). "%d" % 45 == '45'
%i Same as %d. "%i" % 45 == '45'
%o Octal number. "%o" % 1000 == '1750'
%u Unsigned decimal. "%u" % -1000 == '-1000'
%x Hexadecimal lowercase. "%x" % 1000 == '3e8'
%X Hexadecimal uppercase. "%X" % 1000 == '3E8'
%e Exponential notation, lowercase 'e'. "%e" % 1000 == '1.000000e+03'
%E Exponential notation, uppercase 'E'. "%E" % 1000 == '1.000000E+03'
%f Floating point real number. "%f" % 10.34 == '10.340000'
%F Same as %f. "%F" % 10.34 == '10.340000'
%g Either %f or %e, whichever is shorter. "%g" % 10.34 == '10.34'
%G Same as %g but uppercase. "%G" % 10.34 == '10.34'
%c Character format. "%c" % 34 == '"'
%r Repr format (debugging format). "%r" % int == "<type 'int'>"
%s String format. "%s there" % 'hi' == 'hi there'
%% A percent sign. "%g%%" % 10.34 == '10.34%'
ESCAPE DESCRIPTION EXAMPLE
%d 格式化整数 (不包含浮点数). "%d" % 45 == '45'
%i 与%d相同 "%i" % 45 == '45'
%o 8进制数字 "%o" % 1000 == '1750'
%u 负数 "%u" % -1000 == '-1000'
%x 小写的十六进制数字 "%x" % 1000 == '3e8'
%X 大写的十六进制数字 "%X" % 1000 == '3E8'
%e 小写 'e'的指数标记 "%e" % 1000 == '1.000000e+03'
%E 大写 'e'的指数标记 "%E" % 1000 == '1.000000E+03'
%f 浮点数 "%f" % 10.34 == '10.340000'
%F 与%f相同 "%F" % 10.34 == '10.340000'
%g %f 或者 %e中较短的一个 "%g" % 10.34 == '10.34'
%G %F 或者 %E中较短的一个 "%G" % 10.34 == '10.34'
%c 字符格式化 "%c" % 34 == '"'
%r 类型格式化 "%r" % int == "<type 'int'>"
%s 字符串格式 "%s there" % 'hi' == 'hi there'
%% 表示百分号% "%g%%" % 10.34 == '10.34%'

操作符号

有些操作符号你可能还不熟悉,不过还是一一看过去,研究一下它们的功能,如果你研究不出来 也没关系,记录下来日后解决。

Operator Description Example
+ Addition 2 + 4 == 6
- Subtraction 2 - 4 == -2
* Multiplication 2 * 4 == 8
** Power of 2 ** 4 == 16
/ Division 2 / 4.0 == 0.5
// Floor division 2 // 4.0 == 0.0
% String interpolate or modulus 2 % 4 == 2
< Less than 4 < 4 == False
> Greater than 4 > 4 == False
<= Less than equal 4 <= 4 == True
>= Greater than equal 4 >= 4 == True
== Equal 4 == 5 == False
!= Not equal 4 != 5 == True
<> Not equal 4 <> 5 == True
( ) Parenthesis len('hi') == 2
[ ] List brackets [1,3,4]
{ } Dict curly braces {'x': 5, 'y': 10}
@ At (decorators) @classmethod
, Comma range(0, 10)
: Colon def X():
. Dot self.x = 10
= Assign equal x = 10
; semi-colon print "hi"; print "there"
+= Add and assign x = 1; x += 2
-= Subtract and assign x = 1; x -= 2
*= Multiply and assign x = 1; x *= 2
/= Divide and assign x = 1; x /= 2
//= Floor divide and assign x = 1; x //= 2
%= Modulus assign x = 1; x %= 2
**= Power assign x = 1; x **= 2
OPERATOR DESCRIPTION EXAMPLE
+ 2 + 4 == 6
- 2 - 4 == -2
* 2 * 4 == 8
** 幂乘 2 ** 4 == 16
/ 2 / 4.0 == 0.5
// 整除,得到除法的商。 2 // 4.0 == 0.0
% 模除,返回除法的余数。 2 % 4 == 2
< 小于 4 < 4 == False
> 大于 4 > 4 == False
<= 小于等于 4 <= 4 == True
>= 大于等于 4 >= 4 == True
== 等于,比较操作对象是否相等。 4 == 5 == False
!= 不等于 4 != 5 == True
<> 不等于 4 <> 5 == True
( ) 括号 len('hi') == 2
[ ] 列表括号 [1,3,4]
{ } 字典括号 {'x': 5, 'y': 10}
@ 装饰符 @classmethod
, 逗号 range(0, 10)
: 冒号 def X():
. Dot self.x = 10
= 赋值等于 x = 10
; 分号 print "hi"; print "there"
+= 加等于 x = 1; x += 2
-= 减等于 x = 1; x -= 2
*= 乘等于 x = 1; x *= 2
/= 除等于 x = 1; x /= 2
//= 整除等于 x = 1; x //= 2
%= 模除等于 x = 1; x %= 2
**= 幂乘等于 x = 1; x **= 2

花一个星期学习这些东西,如果你能提前完成就更好了。我们的目的是覆盖到所有的符号 类型,确认你已经牢牢记住它们。另外很重要的一点是这样你可以找出自己还不知道哪些 东西,为自己日后学习找到一些方向。

阅读代码

现在去找一些 Python 代码阅读一下。你需要自己找代码,然后从中学习一些东西。 你学到的东西已经足够让你看懂一些代码了,但你可能还无法理解这些代码的功能。 这节课我要教给你的是:如何运用你学到的东西理解别人的代码。

首先把你想要理解的代码打印到纸上。没错,你需要打印出来,因为和屏幕输出相比, 你的眼睛和大脑更习惯于接受纸质打印的内容。一次最多打印几页就可以了。

然后通读你打印出来的代码并做好标记,标记的内容包括以下几个方面:

  1. 函数以及函数的功能。
  2. 每个变量的初始赋值。
  3. 每个在程序的各个部分中多次出现的变量。它们以后可能会给你带来麻烦。
  4. 任何不包含 else 的 if 语句。它们是正确的吗?
  5. 任何可能没有结束点的 while 循环。
  6. 最后一条,代码中任何你看不懂的部分都记下来。

接下来你需要通过注解的方式向自己解释代码的含义。解释各个函数的使用方法, 各个变量的用途,以及任何其它方面的内容,只要能帮助你理解代码即可。

最后,在代码中比较难的各个部分,逐行或者逐个函数跟踪变量值。你可以再打印 一份出来,在空白处写出你要“追踪”的每个变量的值。

当你弄明白这段代码是做什么的之后,回到电脑上再读一遍代码,看看能不能找到一些新的东西。多找一些代码练习,直到你能不需要打印代码就能弄懂它们的功能为止。

Study Drills

  1. 什么是“流程图(flow chart)”,画几个试试。
  2. 如果你发现你正在阅读的代码中存在错误,试着进行修正并把你的更改发送给作者。
  3. 不使用纸质打印时,你可以使用注解符号 # 在程序中加入笔记。有时,这可能会帮到下一个阅读代码的人。

Common Student Questions

What's the difference between %d and %i formatting?
没有区别,只不过由于历史原因,人们更喜欢用%d

Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong

results matching ""

    No results matching ""