概要 †
動作環境 †
$ 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