4. 制御構造と関数・オブジェクト¶

条件分岐 (if)¶

In [1]:
# 基本
status = True

# インデントに注意
print('*** Now I am going to check status ***')

# ifによる分岐
if status:
    print('status is True')  # インデントが1段下がる
else:
    print('status is False') # ここも1段下がる

# ここからインデントが戻る
print('*** Checking status is done ***')
*** Now I am going to check status ***
status is True
*** Checking status is done ***
In [2]:
# 入れ子にするなどより細かい制御
a = 1
b = 2
c = 3

print('** A little more complicated example ***')

if a:
    print('a = ', a)
    # ifを入れ子にする
    if a + b > c:
        print('a + b > c')
    elif a + b < c:
        print('a + b < c')
    elif a + b == c:
        # さらに入れ子にする
        if c >= 0:
            print('a + b = c and c >= 0')
        else:
            print('a + b = c and c <  0')
    else:
        # passを使って「何もしない」ことを明示することもできる
        pass
# トップレベルのifに対応するelseは省略
** A little more complicated example ***
a =  1
a + b = c and c >= 0
In [3]:
#
# 論理演算子を使う例
#
print('** Use logical operators for complex conditionals ***')

if a < b and a < c:
    print('a is smaller than both b and c')

if a < b or a < c:
    print('a is smaller than either b or c')

if (a == 1 and a + b == c) or not (a == 1 and b == 2 and c == 3):
    print('example of complex conditional')
** Use logical operators for complex conditionals ***
a is smaller than both b and c
a is smaller than either b or c
example of complex conditional

反復処理 (for)¶

In [4]:
# 一番シンプルな例
for i in range(5):
    print(i)
0
1
2
3
4
In [5]:
# 1つおきのループ
for i in range(0, 5, 2):
    print('i     = ', i)
    print('i + 1 = ', i+1)
i     =  0
i + 1 =  1
i     =  2
i + 1 =  3
i     =  4
i + 1 =  5
In [6]:
# 2重ループの例
for i in range(1, 3):
    for j in range(1, 5):
        print('i = ', i, ', j = ', j, ', i*j = ', i*j)
i =  1 , j =  1 , i*j =  1
i =  1 , j =  2 , i*j =  2
i =  1 , j =  3 , i*j =  3
i =  1 , j =  4 , i*j =  4
i =  2 , j =  1 , i*j =  2
i =  2 , j =  2 , i*j =  4
i =  2 , j =  3 , i*j =  6
i =  2 , j =  4 , i*j =  8
In [7]:
# テイラー展開の公式でsin(x)の近似値を求める
import math

x = 0.2

print('*** Taylor expansion of sin(x) ***')

y = x
a = x
i = 1
print('x = ', x)
print('i = ', i, ' --- sin(x) = ', y)

for i in range(3, 10, 2):
    a = -a / ((i-1)*i) * x**2
    y = y + a
    print('i = ', i, ' --- sin(x) = ', y)

print('exact   --- sin(x) = ', math.sin(x))
*** Taylor expansion of sin(x) ***
x =  0.2
i =  1  --- sin(x) =  0.2
i =  3  --- sin(x) =  0.19866666666666669
i =  5  --- sin(x) =  0.19866933333333336
i =  7  --- sin(x) =  0.19866933079365082
i =  9  --- sin(x) =  0.19866933079506174
exact   --- sin(x) =  0.19866933079506122

反復処理 (while)¶

In [8]:
# 一番シンプルな例
i = 0
while i < 5:
    print(i)
    i += 1
0
1
2
3
4
In [9]:
# テイラー展開の公式でsin(x)の近似値が真の値に十分近づくまで計算する
import math

x = 0.2
i = 1
y = x
a = x
ytrue = math.sin(x)
print('i = ', i, ' --- sin(x) = ', y)

while abs((ytrue - y)/ytrue) > 1.0e-10:
    i += 2
    a = -a / ((i-1)*i) * x**2
    y = y + a
    print('i = ', i, ' --- sin(x) = ', y)

print('approximated = ', y)
print('exact        = ', ytrue)
print('rel. error   = ', abs((ytrue-y)/ytrue))
i =  1  --- sin(x) =  0.2
i =  3  --- sin(x) =  0.19866666666666669
i =  5  --- sin(x) =  0.19866933333333336
i =  7  --- sin(x) =  0.19866933079365082
approximated =  0.19866933079365082
exact        =  0.19866933079506122
rel. error   =  7.0992315183418576e-12

複雑な反復処理¶

In [10]:
i = 1
while True:
    i += 1
    if   i%2 == 0:
        print('Multiple of 2 --- ', i)
        continue
    elif i%3 == 0:
        print('Multiple of 3 --- ', i)
        continue
    elif i%5 == 0:
        print('Multiple of 5 --- ', i)
        continue
    elif i >= 10:
        print('Exit')
        break
    print('Not a multiple of 2, 3, 5 --- ', i)
Multiple of 2 ---  2
Multiple of 3 ---  3
Multiple of 2 ---  4
Multiple of 5 ---  5
Multiple of 2 ---  6
Not a multiple of 2, 3, 5 ---  7
Multiple of 2 ---  8
Multiple of 3 ---  9
Multiple of 2 ---  10
Exit

関数¶

In [11]:
# 関数定義
def square(x):
    return x**2

# 関数呼び出し
square(2.0)
Out[11]:
4.0
In [12]:
### 以下でエラーになるところでも,このセルを2回目以降に評価するときにはエラーにならない!
### エラーになるかどうかをチェックするにはメニューからJupyterカーネルを再起動しよう

# 以下の呼び出しはエラー(この時点ではhelloは定義されていない)
#hello1()

def hello2(name):
    hello1() # 実行時にhello1が定義済みであればOK
    print('I am', name)

# 以下の呼び出しもエラー(この時点ではhello2が呼び出すhello1は定義されていない)
#hello2('John')

def hello1():
    print('Hello')

hello1()
hello2('John')
Hello
Hello
I am John
In [13]:
import math

# approximation of exp(x) via taylor expansion up to order n
def exp_taylor(x, n):
    c = 1.0
    f = 1.0
    for i in range(n):
        c /= (i+1)
        f += c * x**(i+1)
    return f

print('--- exp_taylor ---')
x = 0.5
print('x     = ', x)
print('1st   = ', exp_taylor(x, 1))
print('2nd   = ', exp_taylor(x, 2))
print('3rd   = ', exp_taylor(x, 3))
print('4th   = ', exp_taylor(x, 4))
print('5th   = ', exp_taylor(x, 5))
print('6th   = ', exp_taylor(x, 6))
print('7th   = ', exp_taylor(x, 7))
print('8th   = ', exp_taylor(x, 8))
print('exact = ', math.exp(x))
--- exp_taylor ---
x     =  0.5
1st   =  1.5
2nd   =  1.625
3rd   =  1.6458333333333333
4th   =  1.6484375
5th   =  1.6486979166666667
6th   =  1.6487196180555554
7th   =  1.6487211681547618
8th   =  1.6487212650359622
exact =  1.6487212707001282
In [14]:
# global variables for fibonacci
a =-1
b = 1

def fibonacci():
    # a and b refer to the global variables
    global a, b
    c = a + b
    a = b
    b = c
    return c

print('--- fibonacci ---')
for i in range(20):
    print(fibonacci())
--- fibonacci ---
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181

オブジェクト¶

In [15]:
import sys

# sysオブジェクトの属性versionにアクセス
sys.version
Out[15]:
'3.8.16 | packaged by conda-forge | (default, Feb  1 2023, 16:05:36) \n[Clang 14.0.6 ]'
In [16]:
s = 'python'
In [17]:
# 大文字に変換した文字列を返す
s.upper()
Out[17]:
'PYTHON'
In [18]:
# 小文字に変換した文字列を返す
s.lower()
Out[18]:
'python'
In [19]:
# 先頭を大文字,以降を小文字にした文字列を返す
s.capitalize()
Out[19]:
'Python'
In [ ]: