読者です 読者をやめる 読者になる 読者になる

メモ

Python
  • forループ
>>> a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print i, a[i]
  • whileループ
while i<10:
    print i
    i = i+1

while True:
    pass
  • リスト
>>> a = ['spam', 'eggs', 100, 1234]
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100

append(x)
extend(L)
insert(i, x)
remove(x)
pop([i])
index(x)
count(x)
sort()
reverse()
  • if文
>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'
  • 関数
>>> def fib(n):
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while b < n:
...         print b,
...         a, b = b, a+b

>>> def fib2(n):
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while b < n:
...         result.append(b)
...         a, b = b, a+b
...     return result

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'): return True
        if ok in ('n', 'no', 'nop', 'nope'): return False
        retries = retries - 1
        if retries < 0: raise IOError, 'refusenik user'
        print complaint
  • ラムダ形式
>>> def make_incrementor(n):
...     return lambda x: x + n