python

  • 投稿者:
  • 投稿カテゴリー:python

概要

ドットインストールでお勉強したことをメモ
2015-08-17_225517
http://dotinstall.com/lessons/basic_python_v2

pythonとは

シンプルで取得しやすいオブジェクト指向言語

Hello World

root@hostname:/home/shimizu/python# python --version
Python 2.7.9

root@hostname:/home/shimizu/python# cat hello.py
# coding: UTF-8
# ↑がないと日本語利用時にエラーとなる
print "hello world"

root@hostname:/home/shimizu/python# python hello.py
hello world

変数の型など

root@hostname:/home/shimizu/python# cat hensu.py
# coding: UTF-8
# 変数は大文字小文字を区別する
msg = "hello world"
print msg

# 日本語はuをつける、つけないと文字列操作ができないらしい
msg2 = u"こんにちは"
print msg2

# 改行が必要な場合は """ で加工
print """
this
is
pen
"""
# 演算子 + - * / // % **
# 整数と小数の演算 → 答えは小数となる
# 割り算 → 答えは整数
print 10 * 5
print 10 // 4
print 10 // 4 # 余りを求める
print 2 ** 3
print 10 / 4

# リスト
sales = [25, 50, 70]
print len(sales)
sales[2] = 100
print sales[2]
print range(10)

# リスト操作
sales.sort()
sales.reverse()
print sales

d = "2015/8/15"
print d.split("/")
ds = d.split("/")
print "-".join(ds)

# タプル(変更ができない) "()"で囲む
# 計算時に高速に処理できたり、ミスが少なくなる
# 変更しようとすると以下のエラー
# TypeError: 'tuple' object does not support item assignment
print "tuple"
a = (2,4,8)

# セット(集合型) - 重複を許さない
a = set([1,2,3,4,5,6])
print a

# 辞書型データ key value
fruit = {"apple":100, "banana":200, "pearch":600}
print fruit
print fruit["apple"]
print "banana" in fruit # True or False
print fruit.keys()
print fruit.values()
print fruit.items()

# 組み込み
a = 10
print "age: %d" % a
# オプションも利用可能
print "age: %10d" % a
print "age: %010d" % a

root@hostname:/home/shimizu/python# python hensu.py
hello world
こんにちは

this
is
pen

50
2
2
8
2
3
100
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[100, 50, 25]
['2015', '8', '15']
2015-8-15
tuple
set([1, 2, 3, 4, 5, 6])
{'pearch': 600, 'apple': 100, 'banana': 200}
100
True
['pearch', 'apple', 'banana']
[600, 100, 200]
[('pearch', 600), ('apple', 100), ('banana', 200)]
age: 10
age:         10
age: 0000000010

型の変換に注意

root@hostname:/home/shimizu/python# cat henkan.py
# coding: UTF-8
# 数値 int float
# 文字列 str
print 5 + int("5")
age = 20
print "i am " + str(age) + " years old"

root@hostname:/home/shimizu/python# python henkan.py
10
i am 20 years old

文字列操作

root@hostname:/home/shimizu/python# cat mojisousa.py
# coding: UTF-8
word = "abcdefghijklm"
print len(word)
print word.find("b")
# 2番目から5番目を表示する
print word[2:5]

root@hostname:/home/shimizu/python# python mojisousa.py
13
1
cde

if文

root@hostname:/home/shimizu/python# cat if.py
# coding: UTF-8
score = 50
# if 以下を字下げする
if score > 60:
    print "OK!"
elif score > 40:
    print "SOSO.."
else:
    print "NG!"

root@hostname:/home/shimizu/python# python if.py
SOSO..

ループ文

root@hostname:/home/shimizu/python# cat loop.py
# coding: UTF-8

fruits = ["apple","banana","orange"]
for fruit in fruits:
    print fruit
# for文が終わったら実行する
else:
    print "Finish"

for i in range(4):
    if i ==2:
        continue
    print "number"
    print i
print "Finish"

vegis = {"cabbage":200,"carrot":100,"radish":150}
for key,value in vegis.iteritems():
        print "key:%s value:%d" % (key,value)

for key in vegis.iterkeys():
     print key
for value in vegis.itervalues():
     print value

# while文
print "while"
n = 0
while n < 10:
    print n
    n += 1
else:
    print "Finish"

root@hostname:/home/shimizu/python# python loop.py
apple
banana
orange
Finish
number
0
number
1
number
3
Finish
key:radish value:150
key:cabbage value:200
key:carrot value:100
radish
cabbage
carrot
150
200
100
while
0
1
2
3
4
5
6
7
8
9
Finish

日付操作

root@hostname:/home/shimizu/python# cat datetime.py
# -*- coding: utf-8 -*-
import datetime

if __name__ == "__main__":
    today = datetime.date.today()
    todaydetail = datetime.datetime.today()

    print today
    print todaydetail

    print todaydetail + datetime.timedelta(days=1)

    newyear = datetime.datetime(2016,1,1)
    print newyear

    lastday = newyear - todaydetail
    print lastday.days
root@hostname:/home/shimizu/python# python datetime.py
2015-08-19
2015-08-19 23:07:22.489915
2015-08-20 23:07:22.489915
2016-01-01 00:00:00
134

モジュールの利用

root@hostname:/home/shimizu/python# cat module.py
# coding: UTF-8
import math, random
# 切り上げする
print math.ceil(5.2)
print random.random()

root@hostname:/home/shimizu/python# python module.py
6.0
0.655057714917

関数

root@hostname:/home/shimizu/python# cat function.py
# coding: UTF-8
def hello(name):
    print "hello %s" % name

hello("John")
hello("Agrini")

root@hostname:/home/shimizu/python# python function.py
hello John
hello Agrini

オブジェクト

root@hostname:/home/shimizu/python# cat object.py
# coding: UTF-8
# クラス:オブジェクトの設計図
# インスタンス:クラスを実体化したもの
class User(object):
     def __init__(self,name):
         self.name = name
     def greet(self):
         print "my name is %s!" % self.name

bob = User("Bob")
print bob.name
bob.greet()

# 継承
class SuperUser(User):
    def shout(self):
        print "%s is SUPER!!" % self.name

tom = SuperUser("Tom")
tom.greet()
tom.shout()

root@hostname:/home/shimizu/python# python object.py
Bob
my name is Bob!
my name is Tom!
Tom is SUPER!!