## 2016年7月9日土曜日

### Python - Py Crust: Code Structures(dict, nest, keys method, values method)

• OS X El Capitan - Apple (OS)
• Emacs (Text Editor)
• Python 3.5 (プログラミング言語)

Introducing Python: Modern Computing in Simple Packages (Bill Lubanovic (著)、 O'Reilly Media)のChapter 4(Py Crust: Code Structures)、Things to Do 4.1-12.を取り組んでみる。

Things to Do 4.1-12.

コード(Emacs)

``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- print('4.1') guess_me = 7 if guess_me < 7: print('too low') elif guess_me > 7: print('too high') elif guess_me == 7: print('right') else: raise Exception('?') print('4.2') guess_me = 7 start = 1 while True: if start < 7: print('too low') elif guess_me == 7: print('found it!') break else: raise Exception('?') start += 1 print('4.3') for value in [3, 12, 1, 2]: print(value) print('4.4') print([n for n in range(10) if n % 2 == 0]) print('4.5') print({x: x * x for x in range(10)}) print('4.6') print({x for x in range(10) if x % 2 != 0}) print('4.7') for s in ('Got {0}'.format(n) for n in range(10)): print(s) print('4.8') def good(): return ['Harry', 'Ron', 'Hermione'] print(good()) print('4.9') def get_odds(): for x in range(10): if x % 2 != 0: yield x for i, n in enumerate(get_odds()): if i == 2: print(n) break print('4.10') def test(func): def new_fund(*args, **kwargs): print('start') result = func(*args, **kwargs) print('end') return result return new_fund @test def func(): return 10 n = func() print(n) print('4.11') class OppsException(Exception): pass try: raise OppsException('Caught an oops') except OppsException as err: print(err) print('4.12') titles = ['Creature of Habit', 'Crewel Fate'] plots = ['A nun turns into a monster', 'A haunted yarn shop'] movies = dict(zip(titles, plots)) print(movies) ```

```\$ ./sample.py
4.1
right
4.2
too low
too low
too low
too low
too low
too low
found it!
4.3
3
12
1
2
4.4
[0, 2, 4, 6, 8]
4.5
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
4.6
{1, 3, 5, 9, 7}
4.7
Got 0
Got 1
Got 2
Got 3
Got 4
Got 5
Got 6
Got 7
Got 8
Got 9
4.8
['Harry', 'Ron', 'Hermione']
4.9
5
4.10
start
end
10
4.11
Caught an oops
4.12
{'Creature of Habit': 'A nun turns into a monster', 'Crewel Fate': 'A  haunted yarn shop'}
\$
```