概要 †
動作環境 †
$ python --version
Python 2.7.5
Hello World †
$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> exit()
# coding: UTF-8
# 日本語コメントを記載する場合には文字コードを明記
print "hello world"
$ python hello.py
hello world
変数とデータ型について †
# coding: UTF-8
msg = "hello world" # 変数名は大文字・小文字を区別する
print msg
$ python hello.py
hello world
- データ型の種類
- 数値
- 真偽値 True False
- None
- 関数・オブジェクト
- 要素が並んだもの
- 文字列:文字が並んだもの
- リスト:データが並んだもの
- タプル:データが並んだもの(変更ができない)
- セット:データが並んだもの(重複を許さない)
- 辞書:キーと値がペア
数値を使ってみよう †
- 整数、少数、複素数
- 演算子 + - * / // % **
# coding: UTF-8
print 10 * 5 # 50(乗算)
print 10 // 3 # 3(商)
print 10 % 3 # 1(余り)
print 2 ** 3 # 8(べき乗)
$ python hello.py
50
3
1
8
# coding: UTF-8
print 5 + 2.0
$ python hello.py
7.0
# coding: UTF-8
print 10 / 3
print 10 / 3.0
$ python hello.py
3
3.33333333333
文字列を使ってみよう †
- 文字列はダブルクォートまたはシングルクォートで囲む
- 日本語の文字列の前にはUnicodeの意味の"u"を付ける
- 連結 +
- 繰り返し *
- エスケープ \n \t \\
print "hello" + "world"
print u"無駄!" * 10
print 'hello\n wo\trld\\ it\'s a pen'
# 改行を含む文字列
print """<html lang="ja">
<body>
</body>
</html>"""
$ python hello.py
helloworld
無駄!無駄!無駄!無駄!無駄!無駄!無駄!無駄!無駄!無駄!
hello
wo rld\ it's a pen
<html lang="ja">
<body>
</body>
</html>
len、find、[]を使ってみよう †
s = "abcdefghi"
print len(s)
print s.find("c")
print s.find("x") # 存在しない文字列を指定すると-1を返す
$ python hello.py
9
2
-1
s = "abcdefghi"
print s[2] # 2番目の文字列
print s[2:5] # 2番目〜5番目の文字列
print s[:5] # 0番目〜5番目の文字列
print s[2:] # 2番目〜最後の文字列
print s[2:-1] # 2番目〜末尾から1番目の文字列
$ python hello.py
c
cde
abcde
cdefghi
cdefgh
数値と文字列の相互変換 †
print 5 + int("5")
print 5 + float("5")
$ python hello.py
10
10.0
age = 20
print "i am " + str(age) + " years old!"
$ python hello.py
i am 20 years old!
リストを使ってみよう †
sales = [255, 100, 353, 400, 'aba']
print len(sales) # 4
print sales[2] # 353
sales[2] = 100
print sales[2] # 100
print 100 in sales # 存在チェック(True/False)
$ python hello.py
5
353
100
True
print range(10) # 10未満の数値
print range(3, 10) # 3〜10未満の数値
print range(3, 10, 2) # 3〜10未満の数値。2つ飛ばし。
$ python hello.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[3, 5, 7, 9]
sort、reverse、split、joinを使おう †
# sort / reverse
sales = [50, 100, 80, 45]
sales.sort() # 昇順
sales.reverse() # 逆順。sortと組み合わせることで降順に並び替え可能。
print sales
$ python hello.py
[100, 80, 50, 45]
# split / join
d = "2016/5/4"
print d.split("/")
a = ["a", "b", "c"]
print "-".join(a)
$ python hello.py
['2016', '5', '4']
a-b-c
タプルを使ってみよう †
- タプル:要素の値の変更ができない
- リスト同様にlen + * []を使用することは可能
- リストよりも安全かつ計算速度も速くなる
a = (2, 5, 8)
a[2] = 10
$ python hello.py
Traceback (most recent call last):
File "hello.py", line 4, in <module>
a[2] = 10
TypeError: 'tuple' object does not support item assignment
a = (2, 5, 8)
b = list(a)
print b
c = tuple(b)
print c
$ python hello.py
[2, 5, 8]
(2, 5, 8)
セットを使ってみよう †
a = set([1, 2, 3, 4, 3, 2]) # 2回目の3と2は無視される
print a
$ python hello.py
set([1, 2, 3, 4])
a = set([1, 2, 3, 4])
b = set([3, 4, 5])
print a - b # 差集合
print a | b # 和集合
print a & b # 積集合
print a ^ b # 排他的論理和
$ python hello.py
set([1, 2])
set([1, 2, 3, 4, 5])
set([3, 4])
set([1, 2, 5])
辞書を使ってみよう †
sales = {"taguchi":200, "fkoji":300, "tanaka":500}
print sales # 表示順は順不同
$ python hello.py
{'tanaka': 500, 'taguchi': 200, 'fkoji': 300}
sales = {"taguchi":200, "fkoji":300, "tanaka":500}
print sales["taguchi"]
# 値の変更
sales["fkoji"] = 800
print sales
$ python hello.py
200
{'tanaka': 500, 'taguchi': 200, 'fkoji': 800}
sales = {"taguchi":200, "fkoji":300, "tanaka":500}
# 存在チェック
print "taguchi" in sales # True
# keys, values, items一覧表示
print sales.keys()
print sales.values()
print sales .items()
$ python hello.py
True
['tanaka', 'taguchi', 'fkoji']
[500, 200, 300]
[('tanaka', 500), ('taguchi', 200), ('fkoji', 300)]
文字列にデータを組み込もう †
a = 10
b = 1.234234
c = "taguchi"
d = {"fkoji":200, "tanaka":500}
print "age: %d" % a
print "age: %10d" % a
print "age: %010d" % a
print "age: %f" % b
print "age: %.2f" % b
print "age: %s" % c
$ python hello.py
age: 10
age: 10
age: 0000000010
age: 1.234234
age: 1.23
age: taguchi
# 辞書データの組み込み
a = 10
b = 1.234234
c = "taguchi"
d = {"fkoji":200, "tanaka":500}
print "sales %(fkoji)"
print "%d and %f" % (a, b)
$ python hello.py
sales %(fkoji)
10 and 1.234234
ifで条件分岐をしてみよう †
# 条件分岐 if
# 比較演算子 > < >= ,== !=
# 論理演算子 and or not
score = 70
if score > 60 and score < 80: # if 60 < score < 80: でも可
print "ok!"
$ python hello.py
ok!
# elif else
score = 45
if score > 60:
print "ok!"
elif score > 40:
print "soso..."
else:
print "ng!"
$ python hello.py
soso...
# 1行でif elseを記述する文法
score = 70
print "OK!" if score > 60 else "NG!"
$ python hello.py
OK!
forでループ処理をしてみよう †
sales = [13, 3523, 31, 238]
for sale in sales: # salesから1つずつ値を取得してsaleに代入
print sale
$ python hello.py
13
3523
31
238
sales = [13, 3523, 31, 238]
sum = 0
for sale in sales:
sum += sale
else: # ループ処理を抜けた後に1回だけ実行させたい処理を記述
print sum
$ python hello.py
3805
# range continue breakを使ったfor文
for i in range(10): # 0〜9の数値
if i == 3:
continue # 3をスキップ
if i == 7: # iが7になった場合にループを抜ける
break
print i
$ python hello.py
0
1
2
4
5
6
辞書でループ処理をしてみよう †
users = {"taguchi":200, "fkoji":300, "tanaka":500}
for key, value in users.iteritems():
print "key: %s value: %d" % (key, value)
# keyのみ
for key in users.iterkeys():
print "key: %s" % key
# valueのみ
for value in users.itervalues():
print "key: %d" % value
$ python hello.py
key: tanaka value: 500
key: taguchi value: 200
key: fkoji value: 300
key: tanaka
key: taguchi
key: fkoji
key: 500
key: 200
key: 300
whileでループ処理をしてみよう †
n = 0
while n < 10:
if n == 3:
# break # forループ同様にbreak使用可
n += 1
continue # forループ同様にcontinue使用可
print n
n += 1
else: # forループ同様にelse使用可。breakで抜けた場合はelse以降も呼ばれない
print "end"
$ python hello.py
0
1
2
4
5
6
7
8
9
end
関数を使ってみよう †
def hello():
print "hello"
hello() # 関数の呼び出し
$ python hello.py
hello
def hello(name, num = 3): # numの初期値を指定
print "hello %s! " % name * num
hello("tom", 2) # 2回繰り返し
hello(num = 2, name = "tom") # 引数名を明示的に指定すると順不同で記述可
hello("steve", 4) # 4回繰り返し
hello("steve") # 第2引数省略のため初期値の3回繰り返し
$ python hello.py
hello tom! hello tom!
hello tom! hello tom!
hello steve! hello steve! hello steve! hello steve!
hello steve! hello steve! hello steve!
def hello(name, num = 3):
return "hello %s! " % name * num
s = hello("steve")
print s
$ python hello.py
hello steve! hello steve! hello steve!
変数のスコープとpassについて †
name = "taguchi"
def hello():
name = "fkoji" # ローカル変数nameは関数内のみ有効
print name
$ python hello.py
taguchi
def hello2():
pass # 何もしないという意味
# 他言語ではhello2(){}と記述可能だがpythonはブロックではなくインデントでスコープを指定するため明示的に記述
map、lambdaを使ってみよう †
def double(x):
return x * x
print map(double, [2, 5, 8]) # リスト内の各値に関数の処理を実行
$ python hello.py
[4, 25, 64]
print map(lambda x:x * x, [2, 5, 8]) # map内に関数を直接記述する方法
$ python hello.py
[4, 25, 64]
オブジェクトを作ってみよう †
- オブジェクト:変数と関数をまとめたもの
- クラス:オブジェクトの設計図
- インスタンス:クラスを実体化したもの
class User(object):
def __init__(self, name): # コンストラクタ
self.name = name # インスタンス変数
def greet(self):
print "my name is %s!" % self.name
# インスタンス作成
bob = User("Bob")
tom = User("Tom")
print bob.name
bob.greet()
tom.greet()
$ python hello.py
Bob
my name is Bob!
my name is Tom!
クラスを継承してみよう †
class User(object):
def __init__(self, name):
self.name = name
def greet(self):
print "my name is %s!" % self.name
class SuperUser(User): # Userクラスを継承
def shout(self):
print "%s is SUPER!" % self.name
# インスタンス作成
bob = User("Bob")
tom = SuperUser("Tom")
tom.greet()
tom.shout()
# bob.shout() # エラー発生
$ python hello.py
my name is Tom!
Tom is SUPER!
モジュールを使ってみよう †
import math, random
print math.ceil(5.2) # 6
for i in range(5):
print random.random()
$ python hello.py
6.0
0.765373854242
0.836871053795
0.14922274442
0.338561298359
0.938487349395
from datetime import date # 一部モジュールのみインポートする場合
print date.today()
$ python hello.py
2016-06-25