We’ve migrated our documentation to a new site, which means some URLs have changed.
Audience

Python簡易チュートリアル

このPythonの概要紹介は、Cxenseのドキュメントから Python のコードサンプルをコピペできるようにする、必要に応じてそれらを修正するのに必要最低限をカバーしただけのものです。より詳細なものは 公式のPython サイトにあるこのチュートリアル をご確認ください。

全てのコード例は Python 3.x で、これは2.x と 3.x の両方で記述されている印刷機能を除いて、以下の表で使用されています。

Python スクリプト

スクリプトの出力

学習のポイント

Python 3.x:

print("This is a string")
print(6)

Python 2.x:

print "This is a string"
print 6

This is a string
6

  • Python 2.x は print文があり、Python 3.x は print() 関数がある

  • print() は標準出力で行を書き込む
    (つまり入力に対して行送りを追加し、ターミナルウィンドウに全てをダンプする)

  • Python はコマンドの最後に セミコロン ( ; )のような文字を使わない

  • Pythonではシングル ( ' ) や ダブル ( " )の引用句 で文字列が開始、終了する

  • プリント機能はそれを投げるどんな変数タイプもプリントできる

string = 'Beginning of string'
string += ' and end of string'

for word in string.split():
    print(word)
 
'+'.join(string.split(' '))

Beginning
of
string
and
end
of
string
Beginning+of+string+and+end+of+string


  • 文字列は '+' 演算子を使って連結できる

  • string.split(delimiter)関数は文字列の配列(Pythonではリストと呼ばれる)に変換する。
    デフォルトの区切り文字はスペースなので、string.split() string.split(' ') と同じである。

  • Python に変数の宣言はなく、変数はデータのタイプを取る(時間の経過によって変わる可能性もある)

  • Python で最も一般的に使われる for ループ は for (item in list): someActionWith(item)

  • 全てのクラスの宣言、関数宣言、ループまたは条件はセミコロン( ; )で終わり、そのあとはインデントされなければならない(Python は例えば中括弧のようなブロックの開始/終了のマーカーを使用しない)

  • delimiter.join(listOfStrings)string.split(delimiter) と全く同じ。 後者はいくつかの区切り文字に関連した文字列のリストに分割をし、前者は'接着剤'として付与された区切り文字で文字列のリストを結びつける

def double(input):
    return 2 * input

print(double(3))

6

  • Pythonの関数宣言は def functionName(parameters): 

  • 関数はインデントレベルが関数宣言のレベルに戻ったところで停止する

  • 戻り値は return 文と共に返される

x = 7
if x % 2 == 0:
    print('even number')
else:
    print('odd number')

odd number

  • 条件文は丸括弧で囲む必要はない

  • ifelse の両方のステートメントはコロンで終了し、後続するものはインデントされなければならない

  • 等しいかどうかのテストは ダブルイコール('==') を使う

x = 7
try:
    print(x / 0)
except Exception as e:
    print(str(e))
    raise e
finally:
    print('bye!')

division by zero
bye!

Traceback (most recent call last):
...File "test.py", line 6, in <module>
......raise e
...File "test.py", line 3, in <module>
......print(x / 0)
ZeroDivisionError: division by zero

  • Python では Try/catch/finallytry/except/finally で、 throwraise

  • 例外は 全てのタイプの例外の親クラス

  • str() は任意のオブジェクトの文字列表現を与える

myDict = {'one':1}
print(myDict['one'])
myDict['two'] = 'deux'
print(myDict) 

1
{'one': 1, 'two': 'deux'}

  • ディクショナリは任意のタイプの値を保持できるが、キーはハッシュ可能でなければならない(通常は文字列または数値)

  • 新しいキーと値の組み合わせは dict[newKey] = newValue で追加される

myList = [1, 'string', {'one':1, 'two':2}]
myList.append('one more')
print(myList)

[1, 'string', {'two': 2, 'one': 1}, 'one more']

  • リスト(配列)は任意のタイプのアイテム(要素)を保持できる

  • append() 関数を使ってリストにアイテムを追加する

list = [1, 2, 3, 4, 5]
print([2*x for x in list if x % 2 == 0])

[4, 8]

  • List Comprehensionは 少ないコードで、より多くを表現できるようにする構文で、
    左と下のコードは全く同じことを行なっている

list = [1, 2, 3, 4, 5]
newList = []
for x in list:
	if x % 2 == 0:
		newList.append(2*x) 
print(newList)


ここではそのほとんどを小さなスクリプトでまとめました。出力はどんなものになりますか?

numbers = {'one':'1', 'two': 2, 'three':"3" }
  
def replaceNumbers(inputStr):
    try:
        outputStr = ''
        for word in inputStr.split():
            outputStr += ' '
            if word in numbers:
                outputStr += str(numbers[word])
            else:
                outputStr += word
    except Exception as e:
        print('Something went wrong: ' + str(e))
        outputStr = 'Sorry, better luck another time!'
    finally:
        return outputStr
  
string = "if two wrongs don't make one right, try three"
print(replaceNumbers(string))


if 2 wrongs don't make 1 right, try 3


以下のスクリプトは上のスクリプトと全く同じですが、このバージョンではより使うメモリ量の小さいコードで List Comprehension を使っています。

numbers = {'one':'1', 'two': 2, 'three':"3" }
   
def replaceNumbers(inputStr):
    try:
        outPutstr = ' '.join([str(numbers[word]) if word in numbers else word for word in inputStr.split()])
    except Exception as e:
        print('Something went wrong: ' + str(e))
        outputStr = 'Sorry, better luck another time!'
    finally:
        return outPutstr
   
string = "if two wrongs don't make one right, try three"
print(replaceNumbers(string))


Last updated: