-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLecture_3
More file actions
84 lines (52 loc) · 2.34 KB
/
Lecture_3
File metadata and controls
84 lines (52 loc) · 2.34 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
In this lecture we went over conditional statements, that is, use if statements, and iteration (loops).
A key concept is Boolean contexts. For example:
>>> 4 < 2
False
>>> 5 >= 5
True
And we shall memorize Boolean operators:
>>> True and False
False
>>> True or False
True
>>> not False
True
################
A loop example:
def fib(n):
"""Compute the nth Fibonacci number, for n >= 2. """
pred, curr = 0, 1
k = 2
while k < n:
pred, curr = curr, pred + curr
k = k + 1
return curr
result = fib(8)
################
Programmers use assert statements to verify expectations, such as the output of a function being tested. An assert statement has an expression in a boolean context, followed by a quoted line of text that will be displayed if the expression evaluates to a false value.
For example:
assert fib(8) == 13, 'The 8th Fibonacci number should be 13'
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.When it is a false value, assert causes an error that halts execution. When writing Python in files, rather than directly into the interpreter, tests are typically written in the same file or a neighboring file with the suffix _test.py. That is, you won't see the assert's result in interpreter.
########
A new method taught in this lecture is Doctests. The first line of a docstring should contain a one-line description of the function, followed by a blank line. A detailed description of arguments and behavior may follow.
For example:
def sum_naturals(n):
"""Return the sum of the first n natural numbers.
>>> sum_naturals(10)
55
>>> sum_naturals(100)
5050
"""
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total
we can verify this interaction via the doctest module:
from doctest import testmod # confusing with this command, because nothing happened.
testmod()
we can also use this command:
from doctest import run_docstring_examples
run_docstring_examples(sum_naturals, globals(), True)
############
Lecture 3 concluded.
To be honest, I didn't get the last part of this lecture. I don't see the point of running such test. Probably I will find them useful in future, hopefully.