LoginSignup
12
13

More than 5 years have passed since last update.

初めてのpython (データ型、制御文、関数の定義)

Posted at

最近データ分析をする機会が多く、統計計算に良いと聞いたpythonを少し勉強することにしました。
そのときのメモ書きです。ところどころ端折ってます。

[参考]http://docs.python.jp/2/tutorial/index.html

データ型

数値

基本的な演算子は使える。虚数も自然に使うことができる。

>>> 2
2
>>> 2 + 4 # 演算子 +, -, *, /など
6
>>> 5/2 # 整数同士のときは計算結果も整数(切り下げ)
2
>>> 5/2.0 # 浮動小数点数にすると計算結果は浮動小数点数
2.5

>>> 1j * 1J # 虚数はjまたはJ
(-1+0j)
>>> a=1.5+0.5j # 変数の宣言
>>> a.real # 実数部の取得
1.5
>>> a.imag # 虚数部の取得
0.5

文字列

シングルクォートまたはダブルクォートで文字列を示す。特殊文字はバックスラッシュでエスケープ。

>>> 'spam eggs' # シングルクォート
'spam eggs'
>>> "doesn't" # ダブルクォート
"doesn't"
>>> '"Yes," he said.' # シングルクォート内のダブルクォートは表示される
'"Yes," he said.'
>>> "\"Yes,\" he said." # ダブルクォート内のダブルクォートはバックスラッシュでエスケープ
'"Yes," he said.'
>>> '"Isn't," she said.' # シングルクォート内のシングルクォートはエラー
  File "<stdin>", line 1
    '"Isn't," she said.'
          ^
SyntaxError: invalid syntax
>>> '"Isn\'t," she said.' # バックスラッシュを入れてもバックスラッシュごと表示
'"Isn\'t," she said.'

文字列の演算も直感的に行える

>>> word = 'Help' + 'A' # 文字列の足し算
>>> word
'HelpA'
>>> string = 'str' 'ing' # +は省略可能
>>> string
'string'
>>> 'str'.strip() 'ing' # でもこういうときは省略してはいけない
  File "<stdin>", line 1
    'str'.strip() 'ing'
                      ^
SyntaxError: invalid syntax

文字列を添え字で操作することも可能。省略すると適当に補完する

>>> word
'HelpA'
>>> word[4] # index 4, 5文字目を取得
'A'
>>> word[0:2] # index 0,1 を取得
'He'
>>> word[:2] # index 最初~1までを取得
'He'
>>> word[2:] # index 2~最後まで取得
'lpA'
>>> word[-1] # マイナス表記も可能. 末尾からのindex
'A'

文字列への代入は不可能

>>> word[0] = 'x' # 代入しようとするとエラー
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

リスト

カンマで区切りカッコで囲んだものはリストになる。リストの要素の型は統一しなくても良い。リストの入れ子なども可能。

>>> a = ['spam', 'eggs', 100, 1234] # リストの宣言
>>> a
['spam', 'eggs', 100, 1234]
>>> a[3] # indexでの指定も可能
1234
>>> a[0:2] = [] # 要素の削除
>>> a
[100, 1234]
>>> a[1:1] = ['bletch', 'xyzzy'] # 要素の追加
>>> a
[100, 'bletch', 'xyzzy', 1234]

代入

まとめて代入できる。

>>> a, b = 0, 1 # a = 0 と b = 1を実行
>>> a
0
>>> b
1

制御文

if

elifを好きな数だけつけることができる。elseをつけることもできる。
if... elif... elif...がswitch文やcase文の代用となる。

>>> x = int(raw_input("Please enter an integer: ")) # コマンドラインからの入力
Please enter an integer: 42
>>> if x < 0: # if文のはじまり
...     x = 0
...     print 'Negative changed to zero'
... elif x == 0: # elifで条件を追加
...     print 'Zero'
... elif x == 1:
...     print 'Single'
... else: # 条件にあてはまらないときはelseに
...     print 'More'
...
More

for

for文はリストや文字列に対して反復処理をおこなう

>>> a = ['cat', 'window', 'defenestrate']
>>> for x in a: # aの要素それぞれに対して反復処理
...     print x, len(x) # len()で長さを取得
...
cat 3
window 6
defenestrate 12

数列にわたって反復を行うとき、range()関数を利用することができる。

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5,10) # 範囲を指定して利用
[5, 6, 7, 8, 9]
>>> range(1, 10, 2) # 範囲と増えかたを指定して利用
[1, 3, 5, 7, 9]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)): # rangeとlenを使って操作
...     print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb

制御文内で用いられるもの

break

break文は操作を途中で終了するときに使用する。一番内側のforやwhileを抜ける。

>>> # 素数かどうかを調べる
>>> for n in range(2, 10):
...     for x in range(2,n):
...             if n % x == 0:
...                     print n, 'equals', x, '*', n/x
...                     break
...     else:
...             print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

pass

pass文は何もしない。文を書かなければならないが処理がないときに利用。

>>> # 最小のクラス
>>> class MyEmptyClass:
...     pass
...

関数定義

defで関数の宣言を示す。関数を変数に代入することで名前を変えることができる。

>>> # nまでのフィボナッチ数列を出力
>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...             print a, # カンマを打つと出力を改行しない
...             a, b = b, a+b
...
>>> fib(100)
0 1 1 2 3 5 8 13 21 34 55 89
>>> f = fib # 関数を別の名前にする
>>> f(200)
0 1 1 2 3 5 8 13 21 34 55 89 144

値を返すときはreturn。デフォルト引数、キーワード引数が使える。

>>> def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
...     print "-- This parrot wouldn't", action,
...     print " if you put", voltage, "volts through it."
...     print "-- Lovely plumage, the", type
...     print "-- It's", state, "!"
...
>>> parrot(100) # voltage以外はデフォルト値を使う
-- This parrot wouldn't voom  if you put 100 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !
>>> parrot(action = 'VOOOOM', voltage = 100000) # キーワードを指定して渡す
-- This parrot wouldn't VOOOOM  if you put 100000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !

可変長の引数を受け取ることもできる。
*nameを使うと仮引数のリストを越えた位置指定引数の入ったタプルを受け取り、**nameを使うとそれまでの仮引数に対応したものを除くすべてのキーワード引数が入った辞書を受け取る。

>>> def cheeseshop(kind, *arguments, **keywords):
...     print "-- Do you have any", kind, "?"
...     print "-- I'm sorry, we're all out of", kind
...     for arg in arguments:
...             print arg
...     print "-" * 40
...     keys = sorted(keywords.keys())
...     for kw in keys:
...             print kw, ":", keywords[kw]
...
>>> cheeseshop("Limburger",
...            "It's very runny, sir.",              # arguments
...            "It's really very, VERY runny, sir.", # arguments
...            shopkeeper="Michael Palin",           # keywords
...            client="John Cleese",                 # keywords
...            sketch="Cheese Shop Sketch")          # keywords
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
12
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13