4.13 연습문제

4.1

guess_me = 7
if guess_me == 7:
print('just right')
elif guess_me < 7:
print('too low')
else: print('too hight')

just right

4.2

guess_me = 7
start = 8
while True:
if guess_me == start:
print('found it')
break;
elif start > guess_me:
print('oops')
break;
print('too low')
start += 1

oops

4.3

for value in [3, 2, 1, 0]:
print(value)

3 2 1 0

4.4

even_list = [value for value in range(10) if value % 2 == 0]
even_list

[0, 2, 4, 6, 8]

4.5

suqares = {value:value*value for value in range(10)}
suqares

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

4.6

odd_set = {value for value in range(10) if value % 2 ==1 }
odd_set

{1, 3, 5, 7, 9}

4.7

for thing in ('Got %s' % number for number in range(10)):
print(thing)

Got 0 Got 1 Got 2 Got 3 Got 4 Got 5 Got 6 Got 7 Got 8 Got 9

‘Got %s’ % … 제너레이터 컴프리헨션을 이용해 이터러블한 객체를 생성하여 다시 for로 객체를 순회함

4.8

def good():
return list(['Harry', 'Ron', 'Hrmione'])
good()

[‘Harry’, ‘Ron’, ‘Hrmione’]

### 4.9

```python def get_odds(): for number in range(1, 10, 2): yield number

```python
for index, value in enumerate(0o, 1):
if index == 3:
print(f'The index:{index}`s value : {value}')
break

The index:3`s value : 5

4.10

def test(func):
def inner(*args):
print('start')
result = func(*args)
print('end')
return result
return inner
def add(a,b):
print(a + b)
return a + b
decon_add = test(add)
decon_add(1, 4)

start 5 end 5

@test
def add(a,b):
print(a + b)
return a + b
add(1,4)

start 5 end 5

데코레이터랑 클로저를 활용해 내부 함수에서 외부 함수가 가진 객체를 가져와 내부 함수에 있는 기능을 수행하는 것. 이중 외부 함수가 가지고 있는 함수 객체를 불러와 쓰는것이 데코레이터

4.11

class OopsException(Exception):
pass
a = 10
if a > 0:
raise OopsException('Caught an oops')

OopsException Traceback (most recent call last)
<ipython-input-86-fc4ca08130c3> in <module>()
5
6 if a > 0:
----> 7     raise OopsException('Caught an oops')

OopsException: Caught an oops

4.12

titles = ['Creature of Habit', 'Crewel Fate']
plots = ['A nun turns into a mon ster', 'A haunted yarn shop']
moveis = dict(zip(titles, plots))
moveis

{‘Creature of Habit’: ‘A nun turns into a mon ster’, ‘Crewel Fate’: ‘A haunted yarn shop’}

Comments