Pythonの単純文
Publish date: 2021-03-02
Last updated: 2021-03-02
Last updated: 2021-03-02
Pythonの1論理行の文(simple statement)について説明します。
代入文
代入は=で行える。1行に複数の変数を並べて1度に代入できる。
a = 1
b = 2
a , b = b , a
print(a) # => 2
print(b) # => 1タプル、リスト等の要素をまとめて変数で受け取れる。
*を変数の先頭に付与することで、末尾までの要素をタプル、リストとして受け取れる。
array = [1, 2, 3]
a , b , c = array
x , *y = array
print(a) # => 1
print(b) # => 2
print(c) # => 3
print(x) # => 1
print(y) # => [2, 3]累算代入文
計算結果を代入する。
a = 1
a += 2 # a = a+2 = 1+1 => 3
a -= 1 # a = a-1 = 3-1 => 2
a *= 10 # a = a*5 = 2*5 => 20
a /= 2 # a = a/2 = 10/2 => 10.0
a //= 3 # a = a//3 = 10//3 => 3.0
a **= 4 # a = a**4 = 3**4 => 81.0
a %= 7 # a = a%7 = 81%7 => 4.0b = 0b101
b <<= 2 # => 0b10100
b >>= 2 # => 0b101
b &= 0b1001 # => 0b1
b ^= 0b100 # => 0b101
b |= 0b1100 # => 0b1101import文
モジュールの読み込みを行う。
import モジュール名でローカルの名前空間でモジュールが使えるようになる。
import random
random.choice("abcde")asで束縛するモジュールの名称を指定できる。
import random as rand
rand.choice("abcde")from モジュール名 import 識別子でモジュール内にある識別子の名前の参照をローカルで使えるようになる。
from random import choice
choice("abcde")こちらも同様にasで名称を指定できる。
from random import choice as rchoice
rchoice("abcde")continue文
forやwhile文で実行中のループの処理を止めて、次のループ処理を先頭から開始する場合にcontinueを使用します。 else文が指定されている場合、最後に実行が行われます。
numbers = ['one', 'two', 'theree']
for i in range(len(numbers)):
if i == 1:
continue
print(i, numbers[i])
#=> 0 one 2 theree
for i in range(len(numbers)):
if i == 1:
continue
print(i, numbers[i])
else:
print(4, 'last')
#=> 0 one 2 theree 4 lastbreak文
forやwhile文でループを停止する場合にbreakを使用します。 ループ処理は終了するのでelse文が指定されている場合も実行はされません。
numbers = ['one', 'two', 'theree']
for i in range(len(numbers)):
if i == 1:
break
print(i, numbers[i])
#=> 0 one
for i in range(len(numbers)):
if i == 1:
break
print(i, numbers[i])
else:
print(4, 'last')
#=> 0 onepass文
何も実行しない文ですが、構文上必要な場合に記述します。
if a == 0:
print('a is zero')
elif a < 0:
pass
else:
print('a is positive')raise文
例外の送出を行う。raiseの後に式が指定されていない場合、最後に有効になった例外が再送出される。
try:
1 / 0
except Exception as exc:
raise
# ZeroDivisionError式を指定した場合、式の型で例外が発生する。
try:
1 / 0
except Exception as exc:
raise RuntimeError("Error")
# raise RuntimeError("Error") from exc