Last Update 2025/10/12
概要
代入文
sample.py
print("代入文\n");
class TestClass:
n = 1
cls = TestClass()
a = [1, 2, 3, 4, 5]
x1 = 1
print("【x1 = 1】")
print(f"x1 = {x1}({type(x1)})\n")
x2, x3 = (x for x in range(2))
print("【x2, x3 = (x for x in range(2))】")
print(f"x2 = {x2}({type(x2)})")
print(f"x3 = {x3}({type(x3)})\n")
(x4, x5, x6) = (x for x in range(3))
print("【(x4, x5, x6) = (x for x in range(3))】")
print(f"x4 = {x4}({type(x4)})")
print(f"x5 = {x5}({type(x5)})")
print(f"x6 = {x6}({type(x6)})\n")
[x7, x8] = [x for x in range(2)]
print("【[x7, x8] = [x for x in range(2)]】")
print(f"x7 = {x7}({type(x7)})")
print(f"x8 = {x8}({type(x8)})\n")
*x9, x10 = (x for x in range(5))
print("【*x9, x10 = (x for x in range(5))】")
print(f"x9 = {x9}({type(x9)})")
print(f"x10 = {x10}({type(x10)})\n")
x11, *x12, x13 = (x for x in range(5))
print("【x11, *x12, x13 = (x for x in range(5))】")
print(f"x11 = {x11}({type(x11)})")
print(f"x12 = {x12}({type(x12)})")
print(f"x13 = {x13}({type(x13)})\n")
print(f"cls.n = {cls.n}({type(cls.n)})")
cls.n = 2
print("【cls.n = 2】")
print(f"cls.n = {cls.n}({type(cls.n)})\n")
print(f"a = {a}({type(a)})")
print(f"a[1] = {a[1]}({type(a[1])})")
a[1] = 6
print("【a[1] = 6】")
print(f"a = {a}({type(a)})")
print(f"a[1] = {a[1]}({type(a[1])})\n")
print(f"a = {a}({type(a)})")
a[2:5:1] = (x for x in range(3))
print("【a[2:5:1] = (x for x in range(3))】")
print(f"a = {a}({type(a)})")
実行結果
$ python3 sample.py
代入文
【x1 = 1】
x1 = 1(<class 'int'>)
【x2, x3 = (x for x in range(2))】
x2 = 0(<class 'int'>)
x3 = 1(<class 'int'>)
【(x4, x5, x6) = (x for x in range(3))】
x4 = 0(<class 'int'>)
x5 = 1(<class 'int'>)
x6 = 2(<class 'int'>)
【[x7, x8] = [x for x in range(2)]】
x7 = 0(<class 'int'>)
x8 = 1(<class 'int'>)
【*x9, x10 = (x for x in range(5))】
x9 = [0, 1, 2, 3](<class 'list'>)
x10 = 4(<class 'int'>)
【x11, *x12, x13 = (x for x in range(5))】
x11 = 0(<class 'int'>)
x12 = [1, 2, 3](<class 'list'>)
x13 = 4(<class 'int'>)
cls.n = 1(<class 'int'>)
【cls.n = 2】
cls.n = 2(<class 'int'>)
a = [1, 2, 3, 4, 5](<class 'list'>)
a[1] = 2(<class 'int'>)
【a[1] = 6】
a = [1, 6, 3, 4, 5](<class 'list'>)
a[1] = 6(<class 'int'>)
a = [1, 6, 3, 4, 5](<class 'list'>)
【a[2:5:1] = (x for x in range(3))】
a = [1, 6, 0, 1, 2](<class 'list'>)
累算代入文
sample.py
print("累算代入文\n");
x1 = 5
print(f"実行前 x1 = {x1}")
x1 += 1
print("【x1 += 1】")
print(f"x1 = {x1}\n")
x2 = 5
print(f"実行前 x2 = {x2}")
x2 -= 1
print("【x2 -= 1】")
print(f"x2 = {x2}\n")
x3 = 5
print(f"実行前 x3 = {x3}")
x3 *= 2
print("【x3 *= 2】")
print(f"x3 = {x3}\n")
x4 = 10
print(f"実行前 x4 = {x4}")
x4 /= 2
print("【x4 /= 2】")
print(f"x4 = {x4}\n")
x5 = 10
print(f"実行前 x5 = {x5}")
x5 //= 2
print("【x5 //= 2】")
print(f"x5 = {x5}\n")
x6 = 10
print(f"実行前 x6 = {x6}")
x6 %= 3
print("【x6 %= 3】")
print(f"x6 = {x6}\n")
x7 = 5
print(f"実行前 x7 = {x7}")
x7 **= 2
print("【x7 **= 2】")
print(f"x7 = {x7}\n")
x8 = 4096
print(f"実行前 x8 = {x8}")
x8 >>= 1
print("【x8 >>= 1】")
print(f"x8 = {x8}\n")
x9 = 4096
print(f"実行前 x9 = {x9}")
x9 <<= 1
print("【x9 <<= 1】")
print(f"x9 = {x9}\n")
x10 = 0x71
print(f"実行前 x10 = 0x{x10:02X}")
x10 &= 0x5F
print("【x10 &= 0x5F】")
print(f"x10 = 0x{x10:02X}\n")
x11 = 0x71
print(f"実行前 x11 = 0x{x11:02X}")
x11 ^= 0x5F
print("【x11 ^= 0x5F】")
print(f"x11 = 0x{x11:02X}\n")
x12 = 0x71
print(f"実行前 x12 = 0x{x12:02X}")
x12 |= 0x5F
print("【x12 |= 0x5F】")
print(f"x12 = 0x{x12:02X}\n")
実行結果
$ python3 sample.py
累算代入文
実行前 x1 = 5
【x1 += 1】
x1 = 6
実行前 x2 = 5
【x2 -= 1】
x2 = 4
実行前 x3 = 5
【x3 *= 2】
x3 = 10
実行前 x4 = 10
【x4 /= 2】
x4 = 5.0
実行前 x5 = 10
【x5 //= 2】
x5 = 5
実行前 x6 = 10
【x6 %= 3】
x6 = 1
実行前 x7 = 5
【x7 **= 2】
x7 = 25
実行前 x8 = 4096
【x8 >>= 1】
x8 = 2048
実行前 x9 = 4096
【x9 <<= 1】
x9 = 8192
実行前 x10 = 0x71
【x10 &= 0x5F】
x10 = 0x51
実行前 x11 = 0x71
【x11 ^= 0x5F】
x11 = 0x2E
実行前 x12 = 0x71
【x12 |= 0x5F】
x12 = 0x7F
assert文
sample.py(1)
print("assert文1\n");
s = "abc"
assert len(s) < 3
print("表示されない")
実行結果(1)
$ python3 sample.py
assert文1
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 5, in <module>
assert len(s) < 3
^^^^^^^^^^
AssertionError
sample.py(2)
print("assert文2\n");
s = "abc"
assert len(s) < 3, s
print("表示されない")
実行結果(2)
$ python3 sample.py
assert文2
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 5, in <module>
assert len(s) < 3, s
^^^^^^^^^^
AssertionError: abc
pass文
sample.py
print("pass文\n");
class TestClass:
pass # 何もしないが無いとエラー発生
def samp_f():
pass # 何もしないが無いとエラー発生
x = TestClass()
print(f"x = {x}")
print(f"samp_f = {samp_f()}")
実行結果
$ python3 sample.py
pass文
x = <__main__.TestClass object at 0x7f13647aaa50>
samp_f = None
del文
sample.py
print("del文\n");
class TestClass:
pass
x = TestClass()
x01 = 1
print(f"x01 in dir() : {'x01' in dir()}")
del x01
print("【del x01】")
print(f"x01 in dir() : {'x01' in dir()}\n")
x02 = ["ab", "cd", "ef"]
print(f"x02 = {x02}")
del x02[1]
print("【del x02[1]】")
print(f"x02 = {x02}\n")
x03 = ["a", "b", "c", "d", "e"]
print(f"x03 = {x03}")
del x03[1:3:1]
print("【del x03[1:3:1]】")
print(f"x03 = {x03}\n")
x041 = 1
x042 = 2
x043 = 3
print(f"x041 in dir() : {'x041' in dir()}")
print(f"x042 in dir() : {'x042' in dir()}")
print(f"x043 in dir() : {'x043' in dir()}")
del x041, x042, x043
print("【del x041, x042, x043】")
print(f"x041 in dir() : {'x041' in dir()}")
print(f"x042 in dir() : {'x042' in dir()}")
print(f"x043 in dir() : {'x043' in dir()}\n")
x05 = ["a", "b", "c", "d", "e"]
print(f"x05 = {x05}")
del x05[1], x05[1], x05[1]
print("【del x05[1], x05[1], x05[1]】")
print(f"x05 = {x05}\n")
x.test = "abc"
print(f"x.test in dir(x) : {'test' in dir(x)}")
del x.test
print("【del x.test】")
print(f"x.test in dir(x) : {'test' in dir(x)}")
実行結果
$ python3 sample.py
del文
x01 in dir() : True
【del x01】
x01 in dir() : False
x02 = ['ab', 'cd', 'ef']
【del x02[1]】
x02 = ['ab', 'ef']
x03 = ['a', 'b', 'c', 'd', 'e']
【del x03[1:3:1]】
x03 = ['a', 'd', 'e']
x041 in dir() : True
x042 in dir() : True
x043 in dir() : True
【del x041, x042, x043】
x041 in dir() : False
x042 in dir() : False
x043 in dir() : False
x05 = ['a', 'b', 'c', 'd', 'e']
【del x05[1], x05[1], x05[1]】
x05 = ['a', 'e']
x.test in dir(x) : True
【del x.test】
x.test in dir(x) : False
return文
sample.py
print("return文\n");
def retnone():
return
def retval():
return 100
print(f"retnone() : {retnone()}")
print(f"retval() : {retval()}")
実行結果
$ python3 sample.py
return文
retnone() : None
retval() : 100
yield文
sample.py
print("yield文\n");
def func(s):
for i in range(len(s)):
if (i % 2) == 0:
yield s[i]
print(list(func("abcdef")))
実行結果
$ python3 sample.py
yield文
['a', 'c', 'e']
raise文
sample.py(1)
print("raise文1\n");
x = 1
if not isinstance(x, str):
raise
実行結果(1)
$ python3 sample.py
raise文1
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 6, in <module>
raise
RuntimeError: No active exception to reraise
sample.py(2)
print("raise文2\n");
x = 1
if not isinstance(x, str):
raise TypeError(f"type(x) = {type(x)}")
実行結果(2)
$ python3 sample.py
raise文2
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 6, in <module>
raise TypeError(f"type(x) = {type(x)}")
TypeError: type(x) = <class 'int'>
sample.py(3)
print("raise文3\n");
try:
print(aa)
except :
print("***** Errorが発生 *****\n")
raise
実行結果(3)
$ python3 sample.py
raise文3
***** Errorが発生 *****
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 4, in <module>
print(aa)
^^
NameError: name 'aa' is not defined
break文
sample.py
print("break文\n");
for i in range(5):
if i == 3:
break
for j in range(5):
print(i, j)
if i + j == 5:
break
実行結果
$ python3 sample.py
break文
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
continue文
sample.py
print("continue文\n");
for i in range(5):
if i == 3:
continue
for j in range(5):
if i + j == 5:
continue
print(i, j)
実行結果
$ python3 sample.py
continue文
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 4
4 0
4 2
4 3
4 4
import文
sample.py(1)
print("import文1\n");
import types
print(types.NoneType)
print(types.BuiltinFunctionType)
実行結果(1)
$ python3 sample.py
import文1
<class 'NoneType'>
<class 'builtin_function_or_method'>
sample.py(2)
print("import文2\n");
from types import NoneType # types モジュール内の NoneType を直接取り込む
print(NoneType)
print(BuiltinFunctionType) # importされていないのでエラー発生
実行結果(2)
$ python3 sample.py
import文2
<class 'NoneType'>
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 7, in <module>
print(BuiltinFunctionType)
^^^^^^^^^^^^^^^^^^^
NameError: name 'BuiltinFunctionType' is not defined
sample.py(3)
print("import文3\n");
import types as t # モジュールを t という名前としてインポート
print(t.NoneType)
print(t.BuiltinFunctionType)
実行結果(3)
$ python3 sample.py
import文3
<class 'NoneType'>
<class 'builtin_function_or_method'>
sample.py(4)
print("import文4\n");
import testpkg.test.modtest as tst
print(tst.func())
ディレクトリ構成
(__init__.pyは空ファイル)
(__init__.pyは空ファイル)
sample.py
testpkg/
├── __init__.py
└── test
├── __init__.py
├── modtest2.py
└── modtest.py
modtest.py
from . import modtest2
def func():
return type(modtest2.func2)
modtest2.py
def func2():
pass
実行結果(4)
(-B オプション : .pyc ファイルの生成無し)
(-B オプション : .pyc ファイルの生成無し)
$ python3 -B sample.py
import文4
<class 'function'>
global文
sample.py
print("global文\n");
testvar = 1
def func1():
testvar = 2
print(f"func1() : testvar = {testvar}")
def func2():
global testvar
testvar = 3
print(f"func2() : testvar = {testvar}")
func1()
print(f"testvar = {testvar}")
func2()
print(f"testvar = {testvar}")
実行結果
$ python3 sample.py
global文
func1() : testvar = 2
testvar = 1
func2() : testvar = 3
testvar = 3
nonlocal文
sample.py
print("nonlocal文\n");
def func1():
def func11():
nonlocal testvar
testvar = 1
print(f"func11() : testvar = {testvar}")
testvar = 0
print(f"func1() : testvar = {testvar}")
func11()
print(f"func1() : testvar = {testvar}")
testvar = 2
func1()
print(f"testvar = {testvar}")
実行結果
$ python3 sample.py
nonlocal文
func1() : testvar = 0
func11() : testvar = 1
func1() : testvar = 1
testvar = 2
if文
sample.py
import sys
print("if文\n");
if len(sys.argv) > 1:
a1 = sys.argv[1]
usig = a1.isnumeric()
sig = a1[0] == '+' or a1[0] == '-'
if usig or (len(a1) > 1 and sig and a1[1:len(a1)].isnumeric()):
n = int(sys.argv[1])
if n > 0:
print(f"引数は正数 : {n}");
elif n < 0:
print(f"引数は負数 : {n}")
else:
print(f"引数は {n}")
else:
print("引数が数値以外")
else:
print("引数無し")
実行結果
$ python3 sample.py
if文
引数無し
$ python3 sample.py 1
if文
引数は正数 : 1
$ python3 sample.py -1
if文
引数は負数 : -1
$ python3 sample.py 100
if文
引数は正数 : 100
$ python3 sample.py -100
if文
引数は負数 : -100
$ python3 sample.py 0
if文
引数は 0
while文
sample.py
import sys
print("while文\n");
if len(sys.argv) > 1 and sys.argv[1].isnumeric():
imax = int(sys.argv[1])
i = 0
while i < imax:
print(f"{i:02d}")
if len(sys.argv) > 2 and sys.argv[2].isnumeric():
jmax = int(sys.argv[2])
j = 0
while 1:
if j >= jmax:
break
print(f" {j:02d}")
j += 1
i += 1
else:
print("引数無し")
実行結果
$ python3 sample.py 3
while文
00
01
02
$ python3 sample.py 3 3
while文
00
00
01
02
01
00
01
02
02
00
01
02
for文
sample.py
print("for文\n");
print("for i in range(5):")
for i in range(5):
print(f"{i:02d}")
print()
lst = ['a', 'b', 'c', 'd', 'e']
print("for s in lst:")
for s in lst:
print(s)
print()
print("for i in range(5):")
for i in range(5):
print(f"{i:03d}")
if i == 3:
print("break")
break
print()
print("for i in range(3):")
for i in range(3):
print(f"{i:04d}")
else:
print("else")
実行結果
$ python3 sample.py 3
for文
for i in range(5):
00
01
02
03
04
for s in lst:
a
b
c
d
e
for i in range(5):
000
001
002
003
break
for i in range(3):
0000
0001
0002
else
try文
sample.py
print("try文\n");
try:
print("ここはtry節")
print(x)
print("上の行で例外が発生するためこの行は実行されない")
except NameError:
print("except節のNameErrorと一致。この行は実行される\n")
try:
print(x)
except NameError:
print("NameError!!!")
except ValueError:
print("ValueError!!!")
finally:
print("finally節\n")
try:
print("エラーが発生しない")
except NameError:
print("NameError!!!")
except ValueError:
print("ValueError!!!")
finally:
print("finally節\n")
try:
print("ここもエラーが発生しない")
except NameError:
print("NameError!!!")
else:
print("else節")
finally:
print("finally節\n")
try:
print("エラー発生!!!")
print(x)
except ValueError:
print("ValueError!!!")
else:
print("エラー発生時はelse節は実行されない")
finally:
print("finally節。except節に一致するエラー無し。")
print("ここを実行した後にエラーで停止\n")
実行結果
$ python3 sample.py 3
try文
ここはtry節
except節のNameErrorと一致。この行は実行される
NameError!!!
finally節
エラーが発生しない
finally節
ここもエラーが発生しない
else節
finally節
エラー発生!!!
finally節。except節に一致するエラー無し。
ここを実行した後にエラーで停止
Traceback (most recent call last):
File "/home/devusr/hddw/work/testarea/temp00000024_python/sample.py", line 39, in <module>
print(x)
^
NameError: name 'x' is not defined
with文
sample.py
import contextlib
print("with文\n");
print("【with文無し】")
f = open("sample.txt", 'r')
print(f"type(f) = {type(f)}")
dt = f.read()
f.close()
print(f"dt = {dt}", end='')
print(f"(1) f.closed = {f.closed}\n")
print("【with文無し f.close()実行無し】")
f = open("sample.txt", 'r')
print(f"type(f) = {type(f)}")
dt = f.read()
print(f"dt = {dt}", end='')
print(f"(2) f.closed = {f.closed}\n")
f.close()
print("【with open() f.close()実行無し】")
with open("sample.txt", 'r') as f:
dt = f.read()
print(f"type(f) = {type(f)}")
print(f"dt = {dt}", end='')
print(f'(3) 【with文 実行後】 f.closed = {f.closed}\n')
print("【with contextlib.closing() f.close()実行無し】")
f = open("sample.txt", 'r')
dt = f.read()
with contextlib.closing(f):
print(f"(4) 【with文 ブロック内】 f.closed = {f.closed}")
print(f"type(f) = {type(f)}")
print(f"dt = {dt}", end='')
print(f"(5) 【with文 実行後】 f.closed = {f.closed}\n")
print("【with contextlib.closing(open()) f.close()実行無し】")
with contextlib.closing(open("sample.txt", 'r')) as f:
dt = f.read()
print(f"(6) 【with文 ブロック内】 f.closed = {f.closed}")
print(f"type(f) = {type(f)}")
print(f"dt = {dt}", end='')
print(f"(7) 【with文 実行後】 f.closed = {f.closed}\n")
sample.py
text
実行結果
$ python3 sample.py 3
with文
【with文無し】
type(f) = <class '_io.TextIOWrapper'>
dt = text
(1) f.closed = True
【with文無し f.close()実行無し】
type(f) = <class '_io.TextIOWrapper'>
dt = text
(2) f.closed = False
【with open() f.close()実行無し】
type(f) = <class '_io.TextIOWrapper'>
dt = text
(3) 【with文 実行後】 f.closed = True
【with contextlib.closing() f.close()実行無し】
(4) 【with文 ブロック内】 f.closed = False
type(f) = <class '_io.TextIOWrapper'>
dt = text
(5) 【with文 実行後】 f.closed = True
【with contextlib.closing(open()) f.close()実行無し】
(6) 【with文 ブロック内】 f.closed = False
type(f) = <class '_io.TextIOWrapper'>
dt = text
(7) 【with文 実行後】 f.closed = True
match文
sample.py
print("match文\n");
lst = ["abc", "def", -345, 1]
val = 1
for s in lst:
match s:
case '123' | 'abc':
print("OR パターン")
case '234' | 'def' as name1:
print(f"AS パターン {name1}")
case -345 if val == 0:
print(f"ガードが偽となりここは実行されない")
case _:
print(f"ワイルドカードパターン")
実行結果
$ python3 sample.py
match文
OR パターン
AS パターン def
ワイルドカードパターン
ワイルドカードパターン
実行環境
Python 3.12.11
コード例・出力内容中の表記
・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。