1章

対話型シェル

$ python

で実行可能

基本データ

ブール値、数値、文字列の基本操作

$ python

>>> (True and False) or True
True

>>> (3 + 3) * (14 /2)
42.0

>>> 'hello' + ' world'
'hello world'

>>> 'hello world'[6]
'w'

Symbolなんてものはない nilではなく、None

データ構造

$ python

>>> numbers = ['zero', 'one', 'two']
>>> numbers
['zero', 'one', 'two']

>>> numbers[1]
'one'

>>> numbers.extend(['three', 'four'])
>>> numbers
['zero', 'one', 'two', 'three', 'four']

>>> del numbers[:2]
>>> numbers
['two', 'three', 'four']

range

$ python

>>> age = range(18,30)
>>> age
range(18, 30)

>>> list(age)
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

>>> 25 in age
True

>>> 33 in age
False

辞書型

$ python

>>> fruit = { 'a': 'apple', 'b': 'banana', 'c': 'coconut'}
>>> fruit['b']
'banana'

>>> fruit['d'] = 'data'
>>> fruit
{'a': 'apple', 'b': 'banana', 'c': 'coconut', 'd': 'data'}

Proc

Pythonでは、lambda

$ python

>>> multiply = lambda x,y : x * y
>>> multiply(6,9)
54
>>> multiply(2,3)
6

制御フロー

$ python

>>> if 2 < 3:
...   'loss'
... else:
...   'more'
... 
'loss'

caseとかswitchはPythonにないので、愚直にif, elifでやろう

$ python

>>> quantify = lambda number : 'one' if number == 1 else 'a couple' if number == 2 else 'many'

>>> quantify(2)
'a couple'
>>> quantify(10)
'many'
>>> quantify(1)
'one'

# 流石に三項演算子を複数重ねるのはしんどいので、素直に関数化するのが楽

>>> def quantify(number):
...   if number == 1:
...     return'one'
...   elif number == 2:
...     return 'a couple'
...   else:
...     return 'many'
... 
>>> quantify(2)
'a couple'
>>> quantify(10)
'many'
>>> quantify(1)
'one'

while

$ python
>>> x = 1
>>> while x < 1000:
...   x = x * 2
... 
>>> x
1024

オブジェクトとメソッド

関数は上でやったので省略

クラスとモジュール

>>> class Calculator:
...   def divide(self, x, y):
...     return x / y
... 

>>> c = Calculator()
>>> c.__class__.__name__
'Calculator'
>>> c.divide(10, 2)
5.0

継承

>>> class MultiplyCalculator(Calculator): 
...   def multiply(self, x, y):
...     return x * y
... 
>>> mc = MultiplyCalculator()
>>> mc.__class__.__name__
'MultiplyCalculator'
>>> mc.multiply(10, 2)
20
>>> mc.divide(10,2)
5.0

その他の機能

ローカル変数と代入

関数内で宣言したのはローカル変数になる

多重代入

>>> width, height, depth = [1000, 2250, 250]
>>> height
2250

文字列の式展開

>>> "hello {}".format('dlrow'[::-1])
'hello world'

可変長引数のメソッド

>>> def join_with_commas(*words):
...   return ','.join(words)
... 
>>> join_with_commas('one', 'two', 'three')
'one,two,three'

ブロック

pythonは : から始まり、インデントが下がっている箇所

pythonのyeildはrubyのと主従が逆
pythonでは、遅延評価に使ったりする

以下サンプル


$ python

# yieldを使った場合
>>> def yield_sample():
...   for i in range(2):
...     print("print: {}".format(i))
...     yield i
... 
>>> for ys in yield_sample():
...   print(ys)
... 
print: 0
0
print: 1
1

# returnを使った場合
>>> def return_sample():
...   buffer = []
...   for i in range(2):
...     print("print: {}".format(i))
...     buffer.append(i)
...   return buffer
... 
>>> for rs in return_sample():
...   print(rs)
... 
print: 0
print: 1
0
1

モンキーパッチング

あまり安全な方法じゃないから諦めろ

定数の定義

Pythonに定数なんてものはない、大文字の変数が慣習的な定数とすることなっている場合が多いだけ

定数の削除

変数と同じでOK