The new Qiskit Textbook beta is now available. Try it out now
Python 及び Jupyter notebook 入門

Python 及び Jupyter notebook 入門

Pythonは、コンパイル不要なプログラミング言語です。 プログラムを行単位で実行することができます(これは、Notebookを使用する方法です)。ですので、もしプログラミングについて全く知らないのであれば、Pythonはスタート地点として素晴らしい場所になります。現在のバージョンは Python 3であり、本教科書で使用するものです。

Pythonでコーディングする方法の一つは、Jupyter notebookを使用することです。 これはおそらく、プログラミング、文章、および画像を統合する最良の方法です。 Notebookでは、全てがセルにの中に配置されます。 テキスト・セルとコード・セルは最も一般的なものです。 Jupyter notebookとしてこのセクションを表示している場合、現在読んでいるこのテキストはテキスト・セルに配置されています。 コード・セルは、以下にあります。

コード・セルの内容を実行するには、そのセルをクリックし、 Shift + Enter を押します。 または、左側に小さな矢印がある場合は、それをクリックすることもできます。

1 + 1
2

もしJupyter notebookとしてこのセクションを表示している場合は、読み進めると同時に各コード・セルを実行しましょう。

a = 1
b = 0.5
a + b
1.5

上のセルで、二つの変数abを定義し、値を与え、その後足し合わせています。このような単純な計算は、Pythonでとても完結に表記されます。

Pythonの変数は色々な形を取ります。以下にいくつかの例を示します。

an_integer = 42 # Just an integer
a_float = 0.1 # A non-integer number, up to a fixed precision
a_boolean = True # A value that can be True or False
a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text
none_of_the_above = None # The absence of any actual value or variable type

数のほかに、使用できるデータ構造として list があります。

a_list = [0,1,2,3]

Pythonのlistは、様々なタイプを混在させることができます。

a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ]

(Fortranのような言語と違い)Pythonで、listの添字は0から始まります。つまり、上のlistで最初にある42にアクセスするためには、次の様になります。

a_list[0]
42

同じ様なデータ構造として、 tuple があります。

a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' )
a_tuple[0]
42

listとtupleの主な違いは、listの要素は変更できることです。

a_list[5] = 'apple'

print(a_list)
[42, 0.5, True, [0, 1], None, 'apple']

一方、tupleの要素は変更できません。

a_tuple[5] = 'apple'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-42d08f1e5606> in <module>
----> 1 a_tuple[5] = 'apple'

TypeError: 'tuple' object does not support item assignment

また、listの最後に要素を追加できますが、tupleはできません。

a_list.append( 3.14 )

print(a_list)
[42, 0.5, True, [0, 1], None, 'apple', 3.14]

他の便利なデータ構造として、dictionary があります。dictionaryは、それぞれユニークな キー でラベルされた の集合を保存できます。

値のデータタイプは任意です。キーは十分単純(integer, float, Boolean, string)であればよいです。dictionaryは、listにはなれませんが、tupleには なりえ ます。

a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 }

値はキーを使ってアクセスします:

a_dict['This is the key for a value 1']
1

新しいキーと値のペアは、新しいキーに対して新しい値を与えることで追加できます。

a_dict['new key'] = 'new_value'

数値の範囲をループする場合、構文は次の通りです:

for j in range(5):
    print(j)
0
1
2
3
4

デフォルトで0から始まりますので、range(n)に対して、n-1で終わることに注意してください。

'iterable'オブジェクトについてもループすることができます。listの場合は次の通りです:

for j in a_list:
    print(j)
42
0.5
True
[0, 1]
None
apple
3.14

dictionaryの場合は以下の通りです:

for key in a_dict:
    value = a_dict[key]
    print('key =',key)
    print('value =',value)
    print()
key = 1
value = This is the value, for the key 1

key = This is the key for a value 1
value = 1

key = False
value = :)

key = (0, 1)
value = 256

key = new key
value = new_value

条件文はifelifelseを使うと以下の文法で記述できます:

if 'strawberry' in a_list:
    print('We have a strawberry!')
elif a_list[5]=='apple':
    print('We have an apple!')
else:
    print('Not much fruit here!')
We have an apple!

パッケージは次のような行でインポートします:

import numpy

パッケージ numpy は数学的なコーディングに重要です。

numpy.sin( numpy.pi/2 )
1.0

numpyコマンドの前に、numpy.を記述する必要があります。それで、numpyに定義されているコマンドだと実行系が知ることができるのです。コーディングを節約するため、一般的に次の様に記述します:

import numpy as np

np.sin( np.pi/2 )
1.0

このようにすると、短縮名だけが必要となります。ほとんどの人が npを使用しますが、好きなものを使用して構いません。

numpyの全てをそのままインポートする場合は、次の通りです:

from numpy import *

この様にすると、コマンドを直接使うことができます。しかし、パッケージ同士で干渉することがあるので、注意して使用する必要があります。

sin( pi/2 )
1.0

三角関数、線形代数などを実行したい場合は、 numpy を使用できます。 プロットする場合は、 matplotlib を使用してください。 グラフ理論の場合は、 networkx を使用します。 量子コンピューティングの場合は、 qiskit を使用します。 あなたが望むどのようなものに対しても、役立つパッケージがきっとあるでしょう。

どの言語でも知っておくべきことは、関数の作り方です。

do_some_mathsという名前で、Input1Input2 という入力を持ち、the_answerという出力を持つ関数は、次の通りです:

def do_some_maths ( Input1, Input2 ):
    the_answer = Input1 + Input2
    return the_answer

これは次の様に使います:

x = do_some_maths(1,72)
print(x)
73

関数にオブジェクトを指定し、関数がそのオブジェクトの状態を変更するメソッドを呼び出すと、その影響は持続します。 つまり、それがあなたのしたいことであれば、何も返す必要はありません。 例えば、listの append メソッドでこれを確かめてみましょう。

def add_sausages ( input_list ):
    if 'sausages' not in input_list:
        input_list.append('sausages')
print('List before the function')
print(a_list)

add_sausages(a_list) # function called without an output

print('\nList after the function')
print(a_list)
List before the function
[42, 0.5, True, [0, 1], None, 'apple', 3.14]

List after the function
[42, 0.5, True, [0, 1], None, 'apple', 3.14, 'sausages']

乱数は random パッケージを使用すると生成できます。

import random
for j in range(5):
    print('* Results from sample',j+1)
    print('\n    Random number from 0 to 1:', random.random() )
    print("\n    Random choice from our list:", random.choice( a_list ) )
    print('\n')
* Results from sample 1

    Random number from 0 to 1: 0.24483110888696868

    Random choice from our list: [0, 1]


* Results from sample 2

    Random number from 0 to 1: 0.7426371646254912

    Random choice from our list: [0, 1]


* Results from sample 3

    Random number from 0 to 1: 0.7269519228900921

    Random choice from our list: 42


* Results from sample 4

    Random number from 0 to 1: 0.8707823815722878

    Random choice from our list: apple


* Results from sample 5

    Random number from 0 to 1: 0.2731676546693854

    Random choice from our list: True


以上は基本です。いま、あなたに必要なのは検索エンジンであり、Stack Exchangeにおいて聞く価値のあるユーザーを知る知見です。 これで、あなたはPythonで何でも行うことができます。あなたのコードは最も「Pythonic」ではないかもしれませんが、それを気にしているのはPythonistasだけです。