Control
>>> print(None, None)
None None
>>> print(print(1), print(2))
1
2
None None
# execute two print expressions
>>> var = print(1)
>>> var + 4
Type Error! Nonetype and int 
None indicates nothing is returned
- the special value none represents nothing
- a function that doesn't explictly return a value will return None
- None will not be displayed in interactive python intepreter
Function
pure function: just return values
abs, pow. They just calculate the value
non-pure functions: have side effects
print(1). It's return value is None, but display 1 additionally
divide
- true divide: use slash /
- integer divide: //
- mod: %
from operator import truediv, floordiv, mod
truediv(2013, 10)	# 201.3
floordiv(2013, 10)	# 201
mod(2013, 10)		# 3
# more return value of a function
def divide_exact(n, d):
    '''return the quotient and remainder of dividing n by d
    
    # some examples
    >>> q, r = divide_exact(2013, 10)
    >>> q
    201
    >>> r
    3
    '''
    return n // d, n % d
	# from operator import floordiv, mod
    # return floordiv(n, d), mod(n, d)
quotient, remainder = divide_exact(2013, 10)
# write in a line instead of two lines
How can we run interactive interpreter in bash?
python -i doc.py
it will execute the document and python prompt appears in the last line.
you can use the func inside
How to run doctest in bash
def func():
    '''this is a function
    
    >>> a = func()
    >>> a
    5
    '''
    # if you type\
    # >>> a
    # 3
    # it will go wrong: expected 3, but got 5
    return 5
python -m doctest document.py means running the py, if it's right, nothing is displayed
python -m doctest -v document.py
please follow the standard above. don't type -m -v doctest

Conditional Statements
a statement is executed by the interpreter to perform an action
- assignment and def statement
If statement
def absolute_value(x):
    '''Return the absolute value of x.'''
    if x < 0:
        return -x
    elif x == 0:
        return 0
    else:
        return x
# more concise code style
if x > 3:
    return True
else:
    return False
Value
- False value: False, 0, '', [], None(more to come)
- True value: Anything else(True)
read section 1.5.4
Iteration: While and For
always use pythontutor
Instance
prime factorization
def prime_factor(x):
    '''print the prime factor of x in non-decreasing order
    
    >>> prime_factor(8)
    2
    2
    2
    >>> prime_factor(6)
    2
    3
    '''
    while x > 1:
        k = smallest_prime_factor(x)
        x = x // k
        print(k)
        
def smallest_prime_factor(n):
    '''Return the smallest prime factor of n'''
    k = 2
    while n % k != 0:
        k += 1
    return k
Boolean
- True, False
- Not
Not has the highest priority, then and, or has the lowest priority
short-circuit
>>> True or 1/0
True
# instead of printing ZeroDivisionError, it outputs True due to short-circuiting
Priority
and or always return the last value they evaluate, no matter whether they are booleans
>>> True and 'hello'
'hello'
Debugging
Instance
Traceback (most recent call last):
  File "<pyshell#29>", line 3 in <module>
    result = buggy(5)
  File <pyshell#29>", line 5 in buggy
    return f + x
TypeError: unsupported operand type(s) for +: 'function' and 'int'
Traceback Messages
The first line
File "<file name>", line <number>, in <function>
- File name: the file contains the problem
- Number: the line number that causes the problem
- Function
The second line
display the actual line of code that makes the function call
Error Messages
<error type>: <error message>
- Error type: like SyntaxError,TypeError
- Error message: detailed description of what exactly caused the problem
Debugging Techniques
Running doctests
python -m doctest <file>.py	tell you which doctests you failed
python -m doctest file.py -v  also tells which doctests you passed
Using print statement
print('DEBUG: result is', result)
Using specific prefix string 'DEBUG: ' allows cs61a ok to ignore this print statement
Interactive Debugging
python -i file.py enables you to debug in an interactive REPL
PythonTutor
python ok -q question --trace 打开网页
不过不知道为什么,打开的是空白网页
Long-term Debugging
debug = True
if debug:
    print('DEBUG: i is', i)
# when we don't want to see the debugging output, we can turn debug to False
Assert
assert isinstance(x, int)
Error types
SyntaxErrors: Before executing any code, python will check SyntaxErrors
各种思路
Q&A
- 
-what non-pure function do aside from printing, like changing global variables 
- 
a function can not only changing the global variable, but also changing another function, even itself 
- 
intrinsic name and bound name 
- 
>>> abs <built-in function abs> >>> f = abs >>> f <built-in function abs> >>> abs = 4 >>> f <built-in function abs>
- 
function call 
- 
def f def g f(g) # it first call g, evaluate the operand expression # then it calls f. g comes first, you should evaluate the operands first. # it needs to bind g to a name or something
- 
difference between frame and environment 
- 
for every frame there's an environment, for every environment starts with a first frame. An environment is a sequence of frames 
- 
floor, ceiling and round operator 
- 
floor discards decimal and ceiling get up and round operator toggles numbers at point five 
- 
True of False 
- 
in python, any number except zero is true, any string except '' is true 
if 'hello':
 print(7)
My own questions
short-circuit(have solved)
# print two pairs of single quote
>>> True or ''hello''
  File "<stdin>", line 1
    True or ''hello''
              ^
SyntaxError: invalid syntax
# why?
>>> True or ''hello''
Error!
# it will first check the syntax, whether its syntax is right
# translate the source code(src) into byte code
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号