88
Python言語」 はじめの一歩 Takanori Suzuki / 2015-08-19 ヒカ☆ラボ

「Python言語」はじめの一歩 / First step of Python

Embed Size (px)

Citation preview

Page 1: 「Python言語」はじめの一歩 / First step of Python

「Python言語」

はじめの一歩Takanori Suzuki / 2015-08-19

ヒカ☆ラボ

Page 2: 「Python言語」はじめの一歩 / First step of Python
Page 3: 「Python言語」はじめの一歩 / First step of Python

ハッシュタグは #ヒカラボ

Page 4: 「Python言語」はじめの一歩 / First step of Python

自己紹介

• 鈴木 たかのり / Takanori Suzuki

• Twitter: @takanory

Page 5: 「Python言語」はじめの一歩 / First step of Python

PyCon JP 2015 Chair

Page 6: 「Python言語」はじめの一歩 / First step of Python

Python Bouldering部 部長

Page 7: 「Python言語」はじめの一歩 / First step of Python

• Pythonで開発してる会社

• 一部分を書いた→

• http://www.shuwasystem.co.jp/products/7980html/4315.html

BeProud所属

Page 8: 「Python言語」はじめの一歩 / First step of Python

• 2015年4月発売

• 内容はここから主に引用

• 128ページ、1,980円+税

• http://gihyo.jp/book/2015/978-4-7741-7320-7

Pythonエンジニア養成読本

Page 9: 「Python言語」はじめの一歩 / First step of Python

来場ありがとうございます

Page 10: 「Python言語」はじめの一歩 / First step of Python

Pythonでのプログラミングに

興味ある人?

Page 11: 「Python言語」はじめの一歩 / First step of Python

Python 書いたことある人?

Page 12: 「Python言語」はじめの一歩 / First step of Python

他の言語でプログラム 書いたことある人?

Page 13: 「Python言語」はじめの一歩 / First step of Python

プログラム 書いたことない人?

Page 14: 「Python言語」はじめの一歩 / First step of Python

注意事項

Page 15: 「Python言語」はじめの一歩 / First step of Python

今日の内容だけで Python書けるように

ならないよ

Page 16: 「Python言語」はじめの一歩 / First step of Python

今日やること1. Pythonの特徴

2. 言語の特徴

3. インストール

4. 基本的な言語仕様

5. Python 2と3の違い

6. よく使う標準ライブラリ

7. よく使うサードパーティ製パッケージ

8. どうやって学ぶか

Page 17: 「Python言語」はじめの一歩 / First step of Python

1. Pythonの特徴

Page 18: 「Python言語」はじめの一歩 / First step of Python

Q. Pythonってなにができるの?

Page 19: 「Python言語」はじめの一歩 / First step of Python

A. なんでもできます

Page 20: 「Python言語」はじめの一歩 / First step of Python

きれいに書きやすい ので保守しやすい

Page 21: 「Python言語」はじめの一歩 / First step of Python

ちゃんとしてる

• 20年以上開発が継続

• 後方互換性あり

• PEPというルールに則って機能を拡張

Page 22: 「Python言語」はじめの一歩 / First step of Python

Python 2 と 3

• 最新は Python 2.7.10 と 3.4.3(もうすぐ3.5.0)

• 一部後方互換性なし

• 今日は Python 3 ベースでやります

Page 23: 「Python言語」はじめの一歩 / First step of Python

2. 言語の特徴

Page 24: 「Python言語」はじめの一歩 / First step of Python

今日やること1. Pythonの特徴

2. 言語の特徴 ← イマココ

3. インストール

4. 基本的な言語仕様

5. Python 2と3の違い

6. よく使う標準ライブラリ

7. よく使うサードパーティ製パッケージ

8. どうやって学ぶか

Page 25: 「Python言語」はじめの一歩 / First step of Python

インデントでブロック構造

for i in range(10): if i % 5 == 0: print('ham') elif i % 3 == 0: print('eggs') else: print('spam')

Page 26: 「Python言語」はじめの一歩 / First step of Python

対話モード$ python Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in range(10): ... if i % 5 == 0: ... print('ham') ... elif i % 3 == 0: ... print('eggs') ... else: ... print('spam') ... ham spam spam : eggs

Page 27: 「Python言語」はじめの一歩 / First step of Python

バッテリー付属

• 200+ の便利な標準ライブラリ

• http://docs.python.jp/3/library/

Page 28: 「Python言語」はじめの一歩 / First step of Python

豊富な外部パッケージ

• 60,000+ の外部パッケージ

• PyPI: Python Package Index

• http://pypi.python.org/

• 「パイピーアイ」と読むらしい

Page 29: 「Python言語」はじめの一歩 / First step of Python

3. インストール

Page 30: 「Python言語」はじめの一歩 / First step of Python

python.orgからdownload

• Mac, Windowsはインストーラーからどうぞ

• https://www.python.org/downloads/

• WindowsはPATHの設定をお忘れなく

• Linux はそれぞれのパッケージ管理からどうぞ

Page 31: 「Python言語」はじめの一歩 / First step of Python

4. 基本的な言語仕様

Page 32: 「Python言語」はじめの一歩 / First step of Python

今日やること1. Pythonの特徴

2. 言語の特徴

3. インストール

4. 基本的な言語仕様 ← イマココ

5. Python 2と3の違い

6. よく使う標準ライブラリ

7. よく使うサードパーティ製パッケージ

8. どうやって学ぶか

Page 33: 「Python言語」はじめの一歩 / First step of Python

対話モードで数値計算$ python >>> 1 + 1 2 >>> 2 * 3 6 >>> width = 60 >>> height = 90 >>> width * height 5400

Page 34: 「Python言語」はじめの一歩 / First step of Python

文字列とリスト

>>> ‘Hello world' ‘Hello world' >>> "Monty Python's Flying Circus" "Monty Python's Flying Circus" >>> ['Hello', 3] ['Hello', 3]

Page 35: 「Python言語」はじめの一歩 / First step of Python

関数と組み込み関数

>>> def add(a, b): ... return a + b ... >>> add(1, 3) 4 >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Page 36: 「Python言語」はじめの一歩 / First step of Python

FizzBuzzで知る言語仕様

• 1から順番に数字を言う

• 3で割り切れる時は「Fizz」と言う

• 5で割り切れる時は「Buzz」と言う

• 3と5で割り切れる時は「FizzBuzz」と言う

Page 37: 「Python言語」はじめの一歩 / First step of Python

Pythonファイルを実行def fizzbuzz(num): return num

print(fizzbuzz(4))

$ python fizzbuzz.py 4

Page 38: 「Python言語」はじめの一歩 / First step of Python

for: ループ処理def fizzbuzz(num): return num

for num in range(1, 101): print(fizzbuzz(num))

$ python fizzbuzz.py 1 2 3 : 100

Page 39: 「Python言語」はじめの一歩 / First step of Python

if, elif, else: 条件分岐def fizzbuzz(num): if num % 3 == 0 and num % 5 == 0: return 'FizzBuzz' elif num % 3 == 0: return 'Fizz' elif num % 5 == 0: return 'Buzz' else: return str(num)

Page 40: 「Python言語」はじめの一歩 / First step of Python

FizzBuzzの完成$ python fizzbuzz.py 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz : Buzz

Page 41: 「Python言語」はじめの一歩 / First step of Python

その他の言語仕様• データ型

• 文字列の操作

• コレクション

• ファイル操作

• モジュール

Page 42: 「Python言語」はじめの一歩 / First step of Python

データ型

• int: 整数型

• float: 浮動小数点型

• str: 文字列型

• bytes: バイト型

Page 43: 「Python言語」はじめの一歩 / First step of Python

データ型>>> type(1) <class 'int'> >>> type(1.1) <class 'float'> >>> type('日本語') <class 'str'> >>> '日本語'.encode('utf-8') b'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e' >>> type('日本語'.encode('utf-8')) <class 'bytes'>

Page 44: 「Python言語」はじめの一歩 / First step of Python

文字列の操作>>> 'Hello World' # シングルクォーテーション 'Hello World' >>> "Hello World" # ダブルクォーテーション 'Hello World' >>> 'Mt.' + 'Fuji' # 文字列の連結 'Mt.Fuji' >>> 'python'[2:5] # スライス 'tho' >>> 't' in 'python' # 文字列の存在チェック True >>> 'pain-au-chocolat'.split('-') # 文字列分割 ['pain', 'au', 'chocolat']

Page 45: 「Python言語」はじめの一歩 / First step of Python

コレクション

• list: リスト

• tuple: タプル

• dict: 辞書

• set: 集合

Page 46: 「Python言語」はじめの一歩 / First step of Python

list: リスト>>> animals = ['cat', 'dog', 'snake'] >>> type(animals) <class 'list'> >>> animals[0] # 要素を取得 'cat' >>> animals[1:] # スライスも使える ['dog', 'snake'] >>> animals.append('elephant') # 要素を追加 >>> for animal in animals: # ループで取り出す ... print(animal) ... cat dog snake elephant

Page 47: 「Python言語」はじめの一歩 / First step of Python

tuple: タプル>>> animals = ('cat', 'dog', 'snake') >>> type(animals) <class 'tuple'> >>> animals[0] # 要素を取得 'cat' >>> animals[1:] # スライスも使える ('dog', 'snake') >>> animals.append('elephant') # 追加はエラー Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append' >>> 'spam', # 要素が一つのtupleを作成 ('spam',)

Page 48: 「Python言語」はじめの一歩 / First step of Python

dict: 辞書>>> user_info = { ... 'firstname': 'takanori', ... 'lastname': 'suzuki', ... } >>> user_info {'firstname': 'takanori', 'lastname': 'suzuki'} >>> user_info['firstname'] # 要素を取得 'takanori' >>> 'firstname' in user_info # キーの存在チェック True >>> for key, value in user_info.items(): ... print(key, value) ... firstname takanori lastname suzuki

Page 49: 「Python言語」はじめの一歩 / First step of Python

set: 集合>>> {'spam', 'ham'} {'ham', 'spam'} >>> {'spam', 'spam', 'spam'} {'spam'} >>> set1 = {'spam', 'ham'} >>> set2 = {'ham', 'eggs'} >>> set1 & set2 # 集合の積 {'ham'} >>> set1 | set2 # 集合の和 {'ham', 'eggs', 'spam'}

Page 50: 「Python言語」はじめの一歩 / First step of Python

ファイル操作>>> with open('todo.txt') as f: # ファイルを開く ... todo_str = f.read() ... >>> with open('memo.txt', 'w') as f: # 書き込む ... f.write('Hello world\n') ... 12 >>> with open('memo.txt', 'a', encoding='utf-8') as f: # 文字コード指定して追記 ... f.write('こんにちは世界\n') ... 8

Page 51: 「Python言語」はじめの一歩 / First step of Python

モジュールdef add(a, b): return a + b def sub(a, b): return a - b

>>> import calc >>> calc.add(1, 3) 4 >>> from calc import sub >>> sub(5, 2) 3

calc.py

Page 52: 「Python言語」はじめの一歩 / First step of Python

5. Python 2 と 3 の違い

Page 53: 「Python言語」はじめの一歩 / First step of Python

今日やること1. Pythonの特徴

2. 言語の特徴

3. インストール

4. 基本的な言語仕様

5. Python 2と3の違い ← イマココ

6. よく使う標準ライブラリ

7. よく使うサードパーティ製パッケージ

8. どうやって学ぶか

Page 54: 「Python言語」はじめの一歩 / First step of Python

printが文から関数に

>>> print # 空行を出力

>>> print 'Hello Python 2!' Hello Python 2!

Python 2のprint文

Python 3のprint関数>>> print() # 空行を出力

>>> print('Hello Python 3!') Hello Python 3!

Page 55: 「Python言語」はじめの一歩 / First step of Python

文字列がUnicodeに統一Python 2の2種類の文字列

Python 3の文字列は1種類

>>> type('str文字列') <type 'str'> >>> type(u'unicode文字列') <type 'unicode'>

>>> type('str文字列') <class 'str'> >>> type(u'unicode文字列') <class 'str'>

Page 56: 「Python言語」はじめの一歩 / First step of Python

整数の割り算が実数Python 2の整数の割り算の結果は整数

Python 3は浮動小数点数

>>> 4 / 2 2 >>> 1 / 3 0

>>> 4 / 2 2.0 >>> 1 / 3 0.3333333333333333

Page 57: 「Python言語」はじめの一歩 / First step of Python

標準ライブラリの再構成• 名前が変更

• ConfigParser -> configparser

• 統合

• StringIO, cStringIO -> io

• 再構成

• urllib, urllib2, urlparse -> urllib.*

Page 58: 「Python言語」はじめの一歩 / First step of Python

6. よく使う

標準ライブラリ

Page 59: 「Python言語」はじめの一歩 / First step of Python

今日やること1. Pythonの特徴

2. 言語の特徴

3. インストール

4. 基本的な言語仕様

5. Python 2と3の違い

6. よく使う標準ライブラリ← イマココ

7. よく使うサードパーティ製パッケージ

8. どうやって学ぶか

Page 60: 「Python言語」はじめの一歩 / First step of Python

200+ の標準ライブラリ

http://docs.python.jp/3/library/

Page 61: 「Python言語」はじめの一歩 / First step of Python

re: 正規表現>>> import re >>> m = re.search('py(thon)', 'python') >>> m <_sre.SRE_Match object; span=(0, 6), match='python'> >>> m.group() 'python' >>> m.group(0) 'python' >>> m.group(1) 'thon'

Page 62: 「Python言語」はじめの一歩 / First step of Python

sys, os: システムパラメータとOS

>>> import os >>> os.mkdir('spam') >>> os.chdir('spam') >>> os.getcwd() # 現在のディレクトリ '/Users/takanori/hikalab/spam' >>> import sys >>> sys.exit(1)

Page 63: 「Python言語」はじめの一歩 / First step of Python

datetime: 日付と時刻>>> import datetime >>> now = datetime.datetime.now() >>> now.isoformat() '2015-08-17T18:17:49.623626' >>> today = datetime.date(2015, 8, 18) >>> nextyear = datetime.date(2016, 1, 1) >>> delta = nextyear - today >>> delta.days 136

Page 64: 「Python言語」はじめの一歩 / First step of Python

math, random: 数学関数と乱数>>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(2) 1.4142135623730951 >>> import random >>> random.randint(1, 1000) 632 >>> data = ['spam', 'ham', 'eggs'] >>> random.choice(data) 'eggs' >>> random.shuffle(data) >>> data ['spam', 'eggs', 'ham']

Page 65: 「Python言語」はじめの一歩 / First step of Python

itertools: イテレータ生成関数

>>> import itertools >>> list(itertools.chain('ABC', 'DEF')) ['A', 'B', 'C', 'D', 'E', 'F'] >>> list(itertools.combinations('ABCD', 2)) [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

Page 66: 「Python言語」はじめの一歩 / First step of Python

shutil: 高レベルなファイル操作

>>> import shutil >>> shutil.copytree('src_dir', 'dst_dir') >>> shutil.rmtree('src_dir')

Page 67: 「Python言語」はじめの一歩 / First step of Python

json: JSONエンコーダ、デコーダ

>>> import json >>> data = {'spam': 'SPAM', ... 'ham': True, ... 'eggs': None, ... } >>> json_str = json.dumps(data) >>> json_str '{"eggs": null, "ham": true, "spam": "SPAM"}' >>> json.loads(json_str) {'ham': True, 'eggs': None, 'spam': 'SPAM'}

Page 68: 「Python言語」はじめの一歩 / First step of Python

7. よく使う

サードパーティ製 パッケージ

Page 69: 「Python言語」はじめの一歩 / First step of Python

今日やること1. Pythonの特徴

2. 言語の特徴

3. インストール

4. 基本的な言語仕様

5. Python 2と3の違い

6. よく使う標準ライブラリ

7. よく使うサードパーティ製パッケージ← イマココ

8. どうやって学ぶか

Page 70: 「Python言語」はじめの一歩 / First step of Python

60,000+ の

サードパーティ製 パッケージ

https://pypi.python.org/pypi

Page 71: 「Python言語」はじめの一歩 / First step of Python

pipとvirtualenv

• pip: サードパーティ製パッケージをインストールするためのコマンド

• virtualenv: 独立したPython環境を作る

Page 72: 「Python言語」はじめの一歩 / First step of Python

pip のインストール

$ wget https://bootstrap.pypa.io/get-pip.py $ python get-pip.py $ pip install (package name)

Page 73: 「Python言語」はじめの一歩 / First step of Python

virtualenv のインストール$ pip install virtualenv $ virtualenv venv $ . venv/bin/activate (venv)$ pip install requests (venv)$ python >>> import requests >>> quit() (venv)$ deactivate $ python >>> import requests Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'requests'

Page 74: 「Python言語」はじめの一歩 / First step of Python

dateutil: 日時操作の強力な拡張$ pip install python-dateutil

>>> from dateutil.parser import parse >>> parse("Mon Jan 26 20:34:20 UTC 2015") datetime.datetime(2015, 1, 26, 20, 34, 20, tzinfo=tzutc()) >>> parse("2015-01-26 20:34:20 JST") datetime.datetime(2015, 1, 26, 20, 34, 20, tzinfo=tzlocal()) >>> parse("Jan-26-2015") datetime.datetime(2015, 1, 26, 0, 0)

Page 75: 「Python言語」はじめの一歩 / First step of Python

Requests: HTTPクライアント$ pip install requests

>>> import requests >>> url = 'http://connpass.com/api/v1/event/?keyword=python' >>> r = requests.get(url) # URLにアクセス >>> print(r.status_code) # ステータスコードを取得 200 >>> for event in r.json()['events'][:3]: # 先頭3件を取得 ... print(event['title']) # イベントのタイトルを取得 ... Python mini hack-a-thon 夏山合宿 2015 SoftLayer Bluemix Summit 2015 コミュニティ運営の秘訣を知りたい人、『Sync Meetup』に集まれ!!

Page 76: 「Python言語」はじめの一歩 / First step of Python

BeautifulSoup4: HTML, XMLパーサ$ pip install beautifulsoup4

>>> from bs4 import BeautifulSoup >>> import requests >>> r = requests.get('http://docs.python.jp/3/library/') >>> soup = BeautifulSoup(r.content, "html.parser") # HTMLパース >>> toctree = soup.find('div', 'toctree-wrapper') # 目次を取得 >>> links = toctree.find_all('a') # aタグを全て取得 >>> len(links) # リンクの数を取得 358 >>> for link in links[:3]: # 先頭3件を取得 ... print(link.text) ... 1. はじめに 2. 組み込み関数 3. 組み込み定数

Page 77: 「Python言語」はじめの一歩 / First step of Python

Pillow: 画像処理ライブラリ$ pip install pillow

>>> from PIL import Image >>> image = Image.open('sample.jpg') # 画像を読み込み >>> half = (image.size[0] / 2, image.size[1] / 2) >>> half = image.resize(half, Image.ANTIALIAS) # 縮小 >>> half.save('sample-half.jpg') # 画像を保存 >>> rotate = image.transpose(Image.ROTATE_90) # 回転 >>> rotate.save('sample-rotate.png') # PNGで保存

Page 78: 「Python言語」はじめの一歩 / First step of Python

コーディング規約• PEP 0008 -- Style Guide for Python Code

• https://www.python.org/dev/peps/pep-0008/

• pep8: コーディング規約のチェック

• autopep8: 自動的にPEP8形式にする

• flake8: pep8 + ソースコードのチェック

Page 79: 「Python言語」はじめの一歩 / First step of Python

Webフレームワーク

• Django: https://www.djangoproject.com/

• Pyramid: http://docs.pylonsproject.org/en/latest/docs/pyramid.html

• Flask: http://flask.pocoo.org/

• Bottle: http://bottlepy.org/

Page 80: 「Python言語」はじめの一歩 / First step of Python

PyData関連• NumPy: 行列計算

• SciPy: 化学計算

• Pandas: データ操作と処理

• matplotlib: データ可視化

• Chiner: 深層学習

Page 81: 「Python言語」はじめの一歩 / First step of Python

その他

• Sphinx: ドキュメント作成

• Ansible: システム構成管理

• pytz: タイムゾーン情報

• paramiko: SSH2接続

Page 82: 「Python言語」はじめの一歩 / First step of Python

8. どうやって学ぶか

Page 83: 「Python言語」はじめの一歩 / First step of Python

Pythonエンジニア養成読本

• これを買って復習しよう

Page 84: 「Python言語」はじめの一歩 / First step of Python

PyCon JP 2015

• https://pycon.jp/2015/ja/

• 10月9日(金): チュートリアル

• 10月10日(土)、11日(日): カンファレンス

• 10月12日(月・祝): 開発スプリント

Page 85: 「Python言語」はじめの一歩 / First step of Python

Web上のテキスト• Pythonチュートリアル

• http://docs.python.jp/3.4/tutorial/

• Dive into Python 3 日本語版

• http://diveintopython3-ja.rdy.jp/

• Python HOWTO

• http://docs.python.jp/3.4/howto/

Page 86: 「Python言語」はじめの一歩 / First step of Python

まとめ

Page 87: 「Python言語」はじめの一歩 / First step of Python

まとめ

• 復習しよう

• コードを書こう

• コミュニティに飛び込もう

Page 88: 「Python言語」はじめの一歩 / First step of Python

Happy Hacking !