lesson 1-Names, Assignment, and User-Defined Functions
1 2 3 4 5 6 7
>>> pi Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pi'isnot defined >>> from math import pi >>> pi 3.141592653589793
这同样适用于函数
1 2 3 4 5
>>> from math import sin >>> sin <built-in function sin> >>> sin(pi/2) 1.0
自定义
1 2 3
>>> httt=99 >>> httt 99
将两者相结合进行多元定义与计算
1 2 3 4 5
>> area,cnt=299*pi,sin(pi/4) >>> area 939.3362034233481 >>> cnt 0.7071067811865476
python ex.py """execute the code""" python -i ex.py """execute the code and enter the python process More important you can use functions in python process which are defined in this code""" python -m doctest ex.py python -m doctext -v ex.py """very important in code by python.it is a way to debug in case of the next situation"""
for example
1 2 3 4 5 6 7 8 9 10
defhaveatry(n,d): """ >>> a 289.1285714285717 >>> b 289 >>> c 1 """ return n/d,n//d,n%d
defhow_big(x): ...: ... if x > 10: ...: ... print('huge') ...: ... elif x > 5: ...: ... return'big' ...: ... elif x > 0: ...: ... print('small') ...: ... else: ...: ... print("nothin'") ...:
question: how_big(12)
answer
huge
analyse: in python print can be used as a return statement in language C
example 2
1 2 3 4
>>> positive = 28 >>> while positive: # If this loops forever, just type Infinite Loop ... print("positive?") ... positive -= 3
answer
infinite loop
analyse: this is a typical example to distinguish python and C.That's because in C '1' and '0' are used as 'True' and 'False' in python
but what should be noted that if ‘0’ in python is treated as False only ‘0’
lectrue3-higher-older functions
lession1-description
generalizing patterns with arguments
to bigin with,let us introduce assert statement
for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
In [1]: defsquare(r): ...: return r*r In [2]: square(11) Out[2]: 121 In [3]: square(-11) Out[3]: 121 # let us introduce assert statement In [4]: defsquare(r): ...: assert(r>0),'r should be positive' ...: return r*r Cell In[4], line 2, in square(r) 1defsquare(r): ----> 2assert(r>0),'r should be positive' 3return r*r
AssertionError: r should be positive
the common structrue among functions may be a computational process,rather than a number
we can use a high-older function to describe some funtcions which have similarities(just like swich-case statement in language C)
for example
1 2 3 4 5 6 7
In [6]: defcobe(k): ...: returnpow(k,3) defsummin(k,term): ...: total,n=0,1 ...: while(n<=k): ...: total,n=total+term(n),n+1 ...: return total
fruits = ["apple", "banana", "cherry"] fruits.append("orange") # Adds "orange" to the end of the list print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'orange'] ``` * extend
Implement the function make_repeater so that make_repeater(func, n)(x) returns func(func(…func(x)…)), where func is applied n times. That is, make_repeater(func, n) returns another function that can then be applied to another argument. For example, make_repeater(square, 3)(42) evaluates to square(square(square(42))).
defcompose1(func1, func2): """Return a function f, such that f(x) = func1(func2(x)).""" deff(x): return func1(func2(x)) return f defmake_repeater(func, n): """Return the function that computes the nth application of func.
>>> add_three = make_repeater(increment, 3) >>> add_three(5) 8 >>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1 243 >>> make_repeater(square, 2)(5) # square(square(5)) 625 >>> make_repeater(square, 4)(5) # square(square(square(square(5)))) 152587890625 >>> make_repeater(square, 0)(5) # Yes, it makes sense to apply the function zero times! 5 """ "*** YOUR CODE HERE ***" f = func if n == 0: return identity for i inrange(n-1): f = compose1(func, f) return f
analyse: 在 Python 中,当我们谈论 “return identity” 的时候,我们通常是在谈论这样一个函数:它的输出(返回值)与输入完全相同。也就是说,对于任何输入值 x,这个函数都返回 x 自身。这样的函数在函数式编程中也被称为 “恒等函数” 或 “identity function
week2
lectrue1-environment diagrammes
lession1-multiple environment
example
1 2 3 4 5 6
In [1]: defsquare(square): ...: return square*square ...:
In [2]: square(11) Out[2]: 121
lession2-Environments for Higher-Order Functions
1 2 3 4 5 6 7 8 9 10
In [1]: defhaveatry(f,x): ...: return f(f(x)) ...:
In [79]: suits Out[79]: ['heat', 'bears', 'tigers', 'suns']
In [80]: suits[0:2] Out[80]: ['heat', 'bears']
In [81]: original_suits Out[81]: ['heat', 'bears', 'tigers', 'suns'] #we can see not only change different name but also change numbers in list which is different from language C
here introduce a special dictionary in python
1 2 3 4 5 6 7 8 9 10 11 12
In [1]: haveatry={'t':1,'pp':98,'fuck':69}
In [2]: haveatry['fuck'] Out[2]: 69
In [3]: haveatry['cao']=96
In [4]: haveatry.pop('pp') Out[4]: 98
In [5]: haveatry Out[5]: {'t': 1, 'fuck': 69, 'cao': 96}
tuples
it means it can’t be changed in python language
but two tuples can add to creat a new tuple
mutation
distinguish idetity and equality:
identity:#exp0# is #exp1#
if result is true both two expression evaluate to the same object
equality:#exp0# == #exp1#
if result is true both two expression evaluate to equal value
In [16]: my_account.intrest=0.08#instance attribute assignment
In [17]: print(my_account.intrest) 0.08
In [18]: print(my_account.balance) 0
In [19]: account.intrest=0.04# class attribute assignment but don't change the result which has completed instance attribute assignment In [20]: print(my_account.intrest) 0.08
In [21]: her_account=account('jj')
In [22]: her_account.intrest Out[22]: 0.04 In [23]: account.intrest=0.05
In [24]: her_account.intrest Out[24]: 0.05
analyse:all these result from ‘intrest’ in class structrue which is diffrent from ‘folder’ and ‘balance’ in class structrue
inheritance
inheritance is a method for relating classes together
most behavior next is shared with the base calss account which means inheritance
In [31]: next(ri) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) Cell In[31], line 1 ----> 1next(ri)
StopIteration: In [34]: ri=iter(r)
In [35]: next(ri) Out[35]: 3
In [36]: for k in ri: ...: print(k) ...: 4 5
analyse:when we take some tips to treat iterator as list or dictionary,they will convert to which and we should reaptedly do iter.
built-in fuctions for iteration
1 2 3 4 5 6 7
map(fuc,iterable): iterate over func(x) for x in iterator filter(func,iterable): iterate over x in iterable if func(x) zip(first_iter,second_iter):iterate over co-indexed (x,y)pairs reversed(sequence):iterate over x in a sequence in reversed_order list(iterable):craet a list containing all x in iterable tuple(iterable:):craet a tuple containing all x in iterable sorted(iterable):craet a sortedlist containing x in iterable
# upon executing a return statement,a generator function exits and cannot yield any values In [9]: deff(x): ...: yield x ...: yield x+1 ...: return ...: yield x+2 ...:
In [10]: list(f(4)) Out[10]: [4, 5] # providing a value to be returned is allowed,but this value is not yielded In [11]: deff(x): ...: yield x ...: yield x+1 ...: return x+2 ...: yield x+3 ...:
In [12]: list(f(4)) Out[12]: [4, 5] # it is possible to access the returned value
In [13]: defg(x): ...: y=yieldfrom f(x) ...: yield y ...: