** 概要 [#dc50af11]

- シンプルで習得しやすいオブジェクト指向言語
- Google App Engine、Django
- 公式サイト: https://www.python.org/

** 動作環境 [#uc1f4fd9]

 $ python --version
 Python 2.7.5

** Hello World [#r9db7290]

- インタラクティブ実行モード(対話モード)

 $ 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()

- スクリプトファイル作成(hello.py)

 # coding: UTF-8
 # 日本語コメントを記載する場合には文字コードを明記
 
 print "hello world"

 $ python hello.py
 hello world

** 変数とデータ型について [#f94eb04d]

- 変数の使い方

 # coding: UTF-8
 msg = "hello world"   # 変数名は大文字・小文字を区別する
 print msg

 $ python hello.py
 hello world

- データ型の種類
-- 数値
-- 真偽値 True False
-- None
-- 関数・オブジェクト
-- 要素が並んだもの
--- 文字列:文字が並んだもの
--- リスト:データが並んだもの
--- タプル:データが並んだもの(変更ができない)
--- セット:データが並んだもの(重複を許さない)
--- 辞書:キーと値がペア

** 数値を使ってみよう [#r26c2163]

- 整数、少数、複素数
- 演算子 + - * / // % **

 # 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

** 文字列を使ってみよう [#r1df6598]

- 文字列はダブルクォートまたはシングルクォートで囲む
- 日本語の文字列の前には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、[]を使ってみよう [#j8e0d44b]

- 文字数 len
- 検索 find

 s = "abcdefghi"
 print len(s)
 print s.find("c")
 print s.find("x")   # 存在しない文字列を指定すると-1を返す

 $ python hello.py
 9
 2
 -1

- 切り出し [] [start:end]

 s = "abcdefghi"
 print s[2]   # 2番目の文字列
 print s[2:5]  # 2番目&#12316;5番目の文字列
 print s[:5]  # 0番目&#12316;5番目の文字列
 print s[2:]  # 2番目&#12316;最後の文字列
 print s[2:-1]  # 2番目&#12316;末尾から1番目の文字列

 $ python hello.py
 c
 cde
 abcde
 cdefghi
 cdefgh

** 数値と文字列の相互変換 [#j52a6dc6]

- 文字列 -> 数値  int float

 print 5 + int("5")
 print 5 + float("5")

 $ python hello.py
 10
 10.0

- 数値 -> 文字列  str

 age = 20
 print "i am " + str(age) + " years old!"

 $ python hello.py
 i am 20 years old!

** リストを使ってみよう [#i5019cf6]

 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

- rangeを使ってリストを自動生成

 print range(10)   # 10未満の数値
 print range(3, 10)  # 3&#12316;10未満の数値
 print range(3, 10, 2)   # 3&#12316;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を使おう [#l542266a]

- 並び替え

 # 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

** タプルを使ってみよう [#w400848d]

- タプル:要素の値の変更ができない
- リスト同様に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)

** セットを使ってみよう [#mac04c74]

- セット(集合体):重複を許さない

 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])

** 辞書を使ってみよう [#a1574ffd]

 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)]

** 文字列にデータを組み込もう [#b8b7c220]

 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で条件分岐をしてみよう [#r8dff3f1]

 # 条件分岐 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でループ処理をしてみよう [#kb0d4262]

 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&#12316;9の数値
 	if i == 3:
 		continue   # 3をスキップ
 	if i == 7:   # iが7になった場合にループを抜ける
 		break
 	print i

 $ python hello.py
 0
 1
 2
 4
 5
 6

** 辞書でループ処理をしてみよう [#ude82c9c]

 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でループ処理をしてみよう [#c353a0b6]

 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

** 関数を使ってみよう [#g9dd6372]

 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について [#c7bbe703]

 name = "taguchi"
 def hello():
 	name = "fkoji"  # ローカル変数nameは関数内のみ有効
 print name

 $ python hello.py
 taguchi

- pass

 def hello2():
 	pass  # 何もしないという意味
 	# 他言語ではhello2(){}と記述可能だがpythonはブロックではなくインデントでスコープを指定するため明示的に記述

** map、lambdaを使ってみよう [#l134a34d]

- リスト <> 関数 map

 def double(x):
 	return x * x
 print map(double, [2, 5, 8])  # リスト内の各値に関数の処理を実行

 $ python hello.py
 [4, 25, 64]

- 無名関数 lambda

 print map(lambda x:x * x, [2, 5, 8])  # map内に関数を直接記述する方法

 $ python hello.py
 [4, 25, 64]

** オブジェクトを作ってみよう [#ca107c7c]

- オブジェクト:変数と関数をまとめたもの
- クラス:オブジェクトの設計図
- インスタンス:クラスを実体化したもの

 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!

** クラスを継承してみよう [#w659ad26]

 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!

** モジュールを使ってみよう [#naa327df]

- モジュール:言語として予め用意されている便利な関数
- モジュール一覧(公式サイト) https://docs.python.org/3/py-modindex.html
- math / randomモジュールを利用

 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


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS