16
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python入門

Last updated at Posted at 2018-01-16

Pythonとは

  軽量なスクリプト型プログラミング言語


特徴

  軽量、対話型


Download

  公式:http://www.python.org


インストール

  •   windows環境変数の設定(自動設定選択可能)
  •   確認:cmdでpython
C:\Users\rakuf\Desktop\wk>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

hellow world(対話モード)

>>> print("hellow world!!!")
hellow world!!!

対話モードの終了

>>> quit()
C:\Users\rakuf\Desktop\wk>

インデント

※注意:ブロックごとにインデントしないと認識ができない。


日本語対応

code指定が必要

test.py
# -*- coding: utf-8 -*-
# 日本語使用が可能

コマンドラインの引数

$ python test.py paramA paramB
test.py
import sys
args = sys.argv
print(args) # ['test.py', 'paramA', 'paramB']
print(args[0]) # ファイル名 ⇒ test.py
print(args[1]) # paramA
print(args[2])  # paramB

変数

test.py
# -*- coding: utf-8 -*-
# 定義
a = 1 # 数値
b = 'ABC' # 文字列
c = [1, 2, 3, 4, 5] # リスト
d = {'apple': 10, 'orange': 20, 'banana': 30}  # 辞書
# 出力
print(a) 
print(b)
print(c) 
print(d)

結果

1
ABC
[1, 2, 3, 4, 5]
{'apple': 10, 'orange': 20, 'banana': 30}

数値

test.py
# -*- coding: utf-8 -*-

# 定義
a = 1 # int
b = 2.0 # float
c = 3 + 4j # complex
d = complex(5,6) # complex
 
# 出力
print(a) 
print(b)
print(c.real) 
print(d.imag)

結果

1
2.0
3.0
6.0

bool

test.py
# -*- coding: utf-8 -*-

# 定義
a = True # 先頭に大文字が必須
b = False # 先頭に大文字が必須
 
# 出力
print(a) 
print(b)

結果

True
False

文字列

test.py
# -*- coding: utf-8 -*-

# 定義
# ''
str_1 = 'this is a string.'
# ""
str_2 = "this is a string."
# ' in string
str_3 = 'we can use \' in a string.'
# " in string
str_4 = "we can use \" in a string."
# /で編集改行
str_5 = "word1\
word2"
# rの使い方
str_6 = "aaa\nbbb"
str_7 = r"aaa\nbbb"
 
# 出力
print(str_1) 
print(str_2) 
print(str_3) 
print(str_4) 
print(str_5) 
print(str_6) 
print(str_7) 

結果

this is a string.
this is a string.
we can use ' in a string.
we can use " in a string.
word1word2
aaa
bbb
aaa\nbbb

文字列のフォーマット(%)

test.py
# -*- coding: utf-8 -*-

errmsg = "Can't open file"
errcode = 12345
msg = "ERROR: %s (%d)" % (errmsg, errcode)
print(msg)

結果

ERROR: Can't open file (12345)

定数

pythonは定数がサポートされていない。


集合型

リスト

test.py
# -*- coding: utf-8 -*-

a = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']

print(a[0])
print(a[3])
print(a[3:5])
print(a[3:])
print(a[:5])

for n in a:
	print(n)

結果

A0
A3
['A3', 'A4']
['A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']
['A0', 'A1', 'A2', 'A3', 'A4']
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9

tuple

test.py
# -*- coding: utf-8 -*-

a = ('A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9')

a[0] = 'A00' # 変更できない

結果

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    a[0] = 'A00'
TypeError: 'tuple' object does not support item assignment

辞書

test.py
# -*- coding: utf-8 -*-

# 定義
d = {'key1':'value1', 'key2':'value2', 'key3':'value3'}

# 出力
print(d['key1'])

for k, v in d.items():
    print(k, v)

for k in d.keys():
    print(k, d[k])

for v in d.values():
    print(v)

結果

value1
key1 value1
key2 value2
key3 value3
key1 value1
key2 value2
key3 value3
value1
value2
value3

Set

test.py
# -*- coding: utf-8 -*-

# 定義
a = set(['red', 'yellow', 'blue'])
b = set(['green', 'white'])

# 出力、計算可能
print(a)
print(b)
print(a - b)
print(a | b)
print(a & b)
print(a ^ b)
print('red' in a)
a.add('black')
print(a)

結果

{'blue', 'yellow', 'red'}
{'white', 'green'}
{'blue', 'yellow', 'red'}
{'blue', 'green', 'yellow', 'red', 'white'}
set()
{'blue', 'red', 'green', 'yellow', 'white'}
True
{'blue', 'yellow', 'black', 'red'}

制御文

if else

test.py
# -*- coding: utf-8 -*-

a = 10
# if文 注意:インデントの一致
if a > 10:
	print('big')
elif a == 10:
	print('10')
else:
	print('small')

結果

10

while

test.py
# -*- coding: utf-8 -*-

n = 0

# while
while n < 5:
	print(n)
	n += 1
else:
	print('end')

結果

0
1
2
3
4
end

for,range

test.py
# -*- coding: utf-8 -*-

for a in [1, 2, 3]:
    print(a)

print('---')
for b in {'one': 1, 'two': 2, 'three': 3}:
    print(b)

print('---')
for c in "123":
    print(c)

print('---')
# range
for d in range(3): #0から
    print(d)

結果

1
2
3
---
one
two
three
---
1
2
3
---
0
1
2

break

test.py
# -*- coding: utf-8 -*-

# break
for n in range(5):
	if n == 3:
		break
	print(n) 

結果

0
1
2

continue

test.py
# -*- coding: utf-8 -*-

# continue
for n in range(5):
	if n == 3:
		continue
	print(n) 

結果

0
1
2
4

例外処理

test.py
# -*- coding: utf-8 -*-

# 例外
str = '123'
try:
    c = str[10] #10なのでIndexErrorが発生
except IOError:
    print('IOError')
except IndexError:
    print('IndexError')
except:  #その他例外
    print('UnknownError')
else:  #例外が発生しない場合
    print('Other')
finally: #常に実行
    print('Finally')

結果

IndexError
Finally

関数

no return

test.py
# -*- coding: utf-8 -*-

# methodの定義
def printAdd(x, y):
	print(x + y)

# methodの実行
printAdd(1, 2)

結果

3

return

test.py
# -*- coding: utf-8 -*-

# methodの定義
def add(x, y):
	return x + y

# methodの実行
print(add(1, 2))

結果

3

default parameter

test.py
# -*- coding: utf-8 -*-

# methodの定義
def repeat_output(msg, n = 3):
	for i in range(n):
		print(msg)

# methodの実行
repeat_output('test1',)
print('-----')
repeat_output('test2', 5)

結果

test1
test1
test1
-----
test2
test2
test2
test2
test2

[*]引数

test.py
# -*- coding: utf-8 -*-

# methodの定義
def methodA(x, y, *args):
    print(x)
    print(y)
    print(args)
    print(args[0])
    print(args[1])

# methodの実行
methodA('x1', 'y1', 'Z1', 'Z2')

結果

x1
y1
('Z1', 'Z2')
Z1
Z2

[**]引数

test.py
# -*- coding: utf-8 -*-

# methodの定義
def methodA(x, y, **args): #辞書型も受ける
    print(x)
    print(y)
    print(args)
    print(args['k1'])
    print(args['k2'])

# methodの実行
args = {'k1':'v1', 'k2':'v2'}
methodA('x1', 'y1', **args) #辞書型も受ける

結果

x1
y1
{'k1': 'v1', 'k2': 'v2'}
v1
v2

複数の戻り値

test.py
# -*- coding: utf-8 -*-

# methodの定義
def plusOne(x, y):
    return x + 1, y + 1

# methodの実行
x, y = plusOne(2, 4)

print(x, y)

結果

3 5

global変数の参照

test.py
# -*- coding: utf-8 -*-

g = 100
 
def method_global():
    print(g)
 
method_global()
print(g)

結果

100
100

global変数の変更失敗

test.py
# -*- coding: utf-8 -*-

g = 100
 
def method_global():
    g = 200 #メソッド内上書き
    print(g)
 
method_global()
print(g)

結果

200
100

global変数の変更成功

test.py
# -*- coding: utf-8 -*-

g = 100
 
def method_global():
    global g #globalを宣言したら、認識される。
    g = 200 #global変数の変更
    print(g)
 
method_global()
print(g)

結果

200
200

Class

classの定義

test.py
# -*- coding: utf-8 -*-

# classの定義
class SampleClass:
    """this is doc""" #for doc
    
    def getName(self):
        return self.name
        
    def setName(self, name):
        self.name = name

# instanceの生成
a = SampleClass()
a.setName('luohao')
print(a.getName())
    

結果

luohao

class変数、instance変数

test.py
# -*- coding: utf-8 -*-

# classの定義
class SampleClass:
    """this is doc""" #for doc
    
    count = 0 #class変数
    
    def __init__(self):# constructor
        SampleClass.count += 1
        
    def getName(self):
        return self.name #instance変数
        
    def setName(self, name):
        self.name = name #instance変数

# instanceの生成
a = SampleClass()
a.setName('luohao1')
print(a.getName(), SampleClass.count)

b = SampleClass()
b.setName('luohao2')
print(b.getName(), SampleClass.count)

結果

luohao1 1
luohao2 2

アクセス制限(__)

test.py
# -*- coding: utf-8 -*-

# classの定義
class SampleClass:
    """this is doc""" #for doc
    
    def __init__(self):# constructor
        self.__name = 'privateName'
    
    def __getName(self):
        return self.__name

# instanceの生成
a = SampleClass()
print(a.__name) # error
print(a.__getName()) # error

結果

AttributeError: 'SampleClass' object has no attribute '__name'

init__と__del

test.py
# -*- coding: utf-8 -*-

# classの定義
class SampleClass:
    def __init__(self):
        print('INIT!')
    def __del__(self):
        print('DELETE!')

x = SampleClass()
del x

結果

INIT!
DELETE!

classの継承

test.py
# -*- coding: utf-8 -*-

# classの定義
class FatherClass:
    def sayFather(self):
        print('im father')

# classの定義
class SonClass(FatherClass): #fatherクラスを継承する
    def saySon(self):
        print('im son')

# instanceの生成
son = SonClass()
son.sayFather()
son.saySon()
    

結果

im father
im son

classの継承のoverride

test.py
# -*- coding: utf-8 -*-

# classの定義
class FatherClass:
    def sayFather(self):
        print('im father')

# classの定義
class SonClass(FatherClass): #fatherクラスを継承する
    def sayFather(self): #override
        print('im son')

# instanceの生成
son = SonClass()
son.sayFather()
    

結果

im son

classの多重継承

test.py
# -*- coding: utf-8 -*-

# classの定義
class FatherClass:
    def sayFather(self):
        print('im father')
        
class MotherClass:
    def sayMother(self):
        print('im mother')

# classの定義
class SonClass(FatherClass, MotherClass): #fatherクラスを継承する
    pass # 何もしない。
    
# instanceの生成
son = SonClass()
son.sayFather()
son.sayMother()
    
    

結果

im father
im mother

Model

modelTest.py
# -*- coding: utf-8 -*-

# model
# classの定義
class ModelClass:
    def printModel(self):
        print('im from model')
        
test.py
# -*- coding: utf-8 -*-


import modelTest #import

# modelからinstanceの生成
a = modelTest.ModelClass()
a.printModel()   

結果

im from model

Package

modelTest.py
# -*- coding: utf-8 -*-

# model
# classの定義
class ModelClass:
    def printModel(self):
        print('im from model')
        
test.py
# -*- coding: utf-8 -*-


import modelTest #import

print(__package__) #パッケージ名
print(__file__) #ファイル名
print(__name__) #モジュール名  

結果

None
test.py
__main__
16
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?