Lecture 3
1.1 Print and None
None :None is displayed by the interpreter as the value of an expressiom.
difference between print() and directly input in python3 interpreter:
eg:
>>>'asdf'
'asdf'
>>>print('asdf')
asdf
>>>None
>>>print(None)
None
>>>print(1,1,1)
1 1 1
>>>1,1,1
1,1,1
>>>print(print(1),print(2))
1
2
None None
None can't be computed,or erroe will be returned.
Pure Functions:just return values.eg.abs(),pow()
Non-Pure Functions:have side-effecs.eg.print()
1.2Mutiple Environment
difference between global frame and local frame.
1.3Misscellaneous Python Feature
(1)Mutiple input and mutiple output.
(2)documentation:dockstring
(usually the first line below the def)
eg.
>>> def pressure(v, t, n):
"""Compute the pressure in pascals of an ideal gas.
Applies the ideal gas law: http://en.wikipedia.org/wiki/Ideal_gas_law
v -- volume of gas, in cubic meters
t -- absolute temperature in degrees kelvin
n -- particles of gas
"""
k = 1.38e-23 # Boltzmann's constant
return n * k * t / v
(3)interactive session
if correct, no output,or provide the error information.
if you wnay see more output,use '-v'.
eg.
def a_plus_abs_b(a, b):
"""Return a+abs(b), but without calling abs.
>>> a_plus_abs_b(2, 3)
5
>>> a_plus_abs_b(2, -3)
5
>>> # a check that you didn't change the return statement!
>>> import inspect, re
>>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M)
['return f(a, b)']
"""
if b < 0:
f = sub
else:
f = add
return f(a, b)
(4)Default values
if no argument bounded,default values are used.
2.1 Conditional Statements
eg.
if x<0:
return -x
elif x==0:
return 0
else:
return x
2.2 Iteration
most important:what information you need to keep track of in order to perform the iteration
e.g.
1 def fib(n):
2 """Compute the nth Fibonacci number, for n >= 2."""
3 pred, curr = 0, 1 # Fibonacci numbers 1 and 2
4 k = 2 # Which Fib number is curr?
5 while k < n:
6 pred, curr = curr, pred + curr
7 k = k + 1
8 return curr
Appendix
new functions
if elif else ; while