CS61A学习记录

Homework

hw01

CS61/CS61A/hw/hw01 at main · zlh123123/CS61 (github.com)

hw01还是一些基础的python语法练习,下面介绍了一个语法现象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.

>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 3+2, 3-2)
1
>>> if_function(3>2, 3+2, 3-2)
5
"""
if condition:
return true_result
else:
return false_result


def with_if_statement():
"""
>>> result = with_if_statement()
47
>>> print(result)
None
"""
if cond():
return true_func()
else:
return false_func()


def with_if_function():
"""
>>> result = with_if_function()
42
47
>>> print(result)
None
"""
return if_function(cond(), true_func(), false_func())


def cond():
"*** YOUR CODE HERE ***"
return False


def true_func():
"*** YOUR CODE HERE ***"
print(42)


def false_func():
"*** YOUR CODE HERE ***"
print(47)

这里涉及到python中的纯函数与非纯函数。对于纯函数而言,其接收输入产生输出,不会产生其他影响;例如abs()函数,只会返回输入值的绝对值。对于非纯函数而言,其除了输入和输出外,还会对系统产生其他影响;例如print()函数,其功能是打印输入值,而其返回值是None

with_if_function()函数中,首先依次运行的是cond()true_func()false_func()三个函数。cond()函数返回Falsetrue_func()函数返回None,并打印42;false_func()函数同理。因此,运行result = with_if_function()后,会同时打印42和47两个值。最后运行print(result)后,打印false_func()对应的返回值None

hw02

Lab

Exam

Project