CS61A(3): Control

This is the lecture note of CS61A - Lecture 3.

The speacial value None represents nothing in Python.

A function that does not explicitly return a value will return None. None is not displayed by the interpreter as the value of an expression.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> 'Go Bears!'
'Go Bears!'
>>> print('Go Bears!')
Go Bears!

>>> None
>>> print(None)
None

>>> print(print(1), print(2))
1
2
None None

print is a non-pure function, it can generate side effects. The value that print returns is always None.

Pure functions are essential for writing concurrent programs, in which multiple call expressions may be evaluated simultaneously.

Multiple Environments

When Python executes a program, different expressions can be evaluated in different environments.

Miscellaneous Python Features

  • division
1
2
3
4
5
6
7
8
9
10
# Division
618 / 10 # 61.8
618 // 10 # 61
618 % 10 # 8

from operator import truediv, floordiv, mod

truediv(618, 10) # 61.8
floordiv(618, 10) # 61
mod(618, 10) # 8
  • multiple return values
1
2
3
# Multiple return values
def divide_exact(n, d):
return n // d, n % d
  • docstring, doctest & default arguments
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Docstrings, doctests, and default arguments

from operator import floordiv, mod

def divide_exact(n, d=10):
"""Return the quotient and remainder of dividing N by D.

>>> quotient, remainder = divide_exact(618)
>>> quotient
61
>>> remainder
8
"""
return floordiv(n, d), mod(n, d)
  • useful command line:
1
2
3
4
5
# interactive with Python file
~$ python3 -i filename.py

# run doctest in the file
~$ python3 -m doctest filename.py

Conditional Statements

A statement is executed by the interpreter to perform an action.

Conditional statements let programs execute different lines of code depending on certain conditions.

  • False values in Python: False, 0, ' ', [ ], None, { }
  • True values in Python: anything else
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Conditional expressions
def absolute_value(x):
"""Return the absolute value of X.

>>> absolute_value(-3)
3
>>> absolute_value(0)
0
>>> absolute_value(3)
3
"""
if x < 0:
return -x
elif x == 0:
return 0
else:
return x

A conditional expression also has the following form:

1
<consequent> if <predicate> else <alternative>

Logic Operators

To evaluate the expression <left> and <right>:

  • Evaluate the subexpression <left>.
  • If the result is a false value v, then the expression evaluates to v.
  • Otherwise, the expression evaluates to the value of the subexpression <right>.
1
2
3
4
5
6
>>> True and 4
4
>>> 0 and True
0
>>> 12 and None and 1/0
None

To evaluate the expression <left> or <right>:

  • Evaluate the subexpression <left>.
  • If the result is a true value v, then the expression evaluates to v.
  • Otherwise, the expression evaluates to the value of the subexpression <right>.
1
2
3
4
5
6
>>> 4 or True
4
>>> 0 or 12
12
>>> False or 2 or 1/0
2
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
# Examples of short- circuiting behavior

def has_big_sqrt(x):
"""Return whether x has a big square root (> 10).

>>> has_big_sqrt(1000)
True
>>> has_big_sqrt(100)
False
>>> has_big_sqrt(0)
False
>>> has_big_sqrt(-1000)
False
"""
# can avoid crash when x is negative
return x > 0 and sqrt(x) > 10

def reasonable(n):
"""Is N small enough that 1/N can be represented?

>>> reasonable(100)
True
>>> reasonable(0)
True
>>> reasonable(-100)
True
>>> reasonable(10 ** 1000)
False
"""
return n == 0 or 1/n != 0.0

Iteration

Iteration means repeating things.

1
2
3
4
5
6
# Summation via while iteration
i, total = 0, 0
while i < 3:
i = i + 1
total = total + i
print(f"i = {i}, total = {total}") # i = 3, total = 6
  • Example: Prime Factorization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def prime_factors(n):
"""Print the prime factors of n in non-decreasing order.

>>> prime_factors(8)
2
2
2
>>> prime_factors(858)
2
3
11
13
"""
while n > 1:
k = smallest_prime_factor(n)
n = n // k
print(k)

def smallest_prime_factor(n):
"""Find the smallest prime k > 1 that evenly divided n."""
k = 2
while n % k != 0:
k += 1
return k