orashi
cippus_sss
CIPPUS_Python 4th week
Yuanzheng Ci, Screw Studio @ DUT,
2017-11-26
import functools
def add(a, b):
return a + b
add(4, 2)
6
plus3 = functools.partial(add, 3)
plus3(4)
7from time import sleep
class CountDown:
def __init__(self, step):
self.step = step
def __next__(self):
"""Return the next element."""
if self.step <= 0:
raise StopIteration
self.step -= 1
return self.step
def __iter__(self):
"""Return the iterator itself."""
return self
if __name__ == "__main__":
print("Counting down:")
for element in CountDown(10):
print('*', element)
sleep(0.2)>>> def fibonacci():
... a, b = 0, 1
... while True:
... yield b
... a, b = b , a + b
...
>>> fib = fibonacci()
>>> fib
<generator object fibonacci at 0x7f6e8615b0f0>
>>> next(fib)
1
>>> next(fib)
1
>>> next(fib)
2
>>> next(fib)
3
>>> next(fib)
5
>>> next(fib)
8
>>> [next(fib) for _ in range(10)]
[13, 21, 34, 55, 89, 144, 233, 377, 610, 987]def psychologist():
print('Please tell me your problems')
while True:
answer = (yield)
....
psy = psychologist()
psy.send('wtf?')>>> def AB():
... yield 'A'
... yield 'B'
... yield from 'CD'
...
>>> ab = AB()
>>> ab
<generator object AB at 0x7f2ff66380a0>
>>> [x for x in ab]
['A', 'B', 'C', 'D']with open(r'somefileName') as somefile:
for line in somefile:
print(line)
# ...more codesomefile = open(r'somefileName')
try:
for line in somefile:
print(line)
# ...more code
finally:
somefile.close()def foo():
passdef sum(*args):
return reduce(add, args, 0)
sum(1, 2, 3)
sum(*[1, 2, 3])
def another_sum(sequence):
return reduce(add, sequence, 0)
another_sum([1, 2, 3])
def wtf(**kwargs):
pass
wtf(this=1)
wtf(my_money=1e10)By orashi
cippus fourth week python meetup