CS 61A 2018 Python学习要点记录 Chapter1
作者:互联网
这门课程的学习主要是在reading中完成的,视频讲解也穿插在了reading中
故按照CS 61A 2018的参考书的章节作为分段,记录章节的重点信息
之前的内容比较简单,故本章从1.5节开始记录
1.5 Control
reading的网址:http://composingprograms.com/pages/15-control.html
1.5.1 Statements
Control statements are statements that control the flow of a program's execution based on the results of logical comparisons.
Statements differ fundamentally from the expressions that we have studied so far. They have no value. Instead of computing something, executing a control statement determines what the interpreter should do next.
statement与expression的区别:
If you want to do something with the result of an expression, you need to say so: you might store it with an assignment statement or return it with a return statement.
1.5.2 Compound Statements
A compound statement is so called because it is composed of other statements.
a header and an indented suite of statements is called a clause. A compound statement consists of one or more clauses:
1.5.3 Defining Functions II: Local Assignment
The effect of an assignment statement is to bind a name to a value in the first frame of the current environment. As a consequence, assignment statements within a function body cannot affect the global frame.
1.5.4 Conditional Statements
Conditional statements:
When executing a conditional statement, each clause is considered in order. The computational process of executing a conditional clause follows.
1)Evaluate the header's expression.
2)If it is a true value, execute the suite. Then, skip over all subsequent clauses in the conditional statement.
Boolean contexts
1.5.5 Iteration
例子:斐波那契数列
# sequence of Fibonacci numbers
# 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
# F(1)=0, F(2)=1,F(3)=1,...
# 0 1 1 2 3 5 8 13
def Fibonacci(n):
if (n==0 or n==1):
return n
pred, curr = 0, 1
k = 2
while(k < n):
curr, pred = pred + curr, curr # 或者 pred, curr = curr, pred + curr
k = k + 1
return curr
print(Fibonacci(5))
notes:
A while statement that does not terminate is called an infinite loop. Press
1.5.6 Testing
Assertions
When the expression being asserted evaluates to a true value, executing an assert statement has no effect. When it is a false value, assert causes an error that halts execution.
例子:
Doctests文档测试
Python provides a convenient method for placing simple tests directly in the docstring of a function.
the first part:contain a one-line description of the function + a blank line
the second part: a detailed description of arguments and behavior
the third part: a sample interactive session that calls the function
有关 doctests Module的介绍:https://blog.csdn.net/qq_40061206/article/details/109074188
notes:
- range()
range(start, stop[, step])
start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5)
stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
range一般是三个参数,最后的1通常省略,前闭后开
标签:1.5,curr,Python,stop,Chapter1,range,2018,statement,statements 来源: https://www.cnblogs.com/jantonyu/p/16277547.html