Pythonステートメントは、Pythonインタープリタによって実行されるコード命令です。
Python Statements Examples
簡単な文の例を見てみましょう。
count = 10
class Foo:
pass
|
Python 複数行ステートメント
Pythonのステートメントは通常1行で書かれます。改行文字が文の終わりを示します。ステートメントが非常に長い場合は、行継続文字(line continuation character)を使って明示的に複数行に分けることができます( )。
それでは、複数行の文の例を見てみましょう。
message = "Hello There.
You have come to the right place to learn Python Programming.
"
"Follow the tutorials to become expert in Python. "
"Don't forget to share it with your friends too."
math_result = 1 + 2 + 3 + 4 +
5 + 6 + 7 + 8 +
9 + 10
print(message)
print(math_result)
|
Python Statements
Pythonは括弧( )、大括弧[ ]、中括弧{ }の内部での複数行の継続をサポートしています。括弧はListで、中括弧は辞書オブジェクトで使用されます。括弧は式、タプル、文字列に使用することができます。
message = ("Hello
"
"Hi
"
"Namaste")
math_result = (1 + 2 + 3 + 4 +
5 + 6 + 7 + 8 +
9 + 10)
prime_numbers_tuple = (2, 3, 5, 7,
11, 13, 17)
list_fruits = ["Apple", "Banana",
"Orange", "Mango"]
dict_countries = {"USA": "United States of America", "IN": "India",
"UK": "United Kingdom", "FR": "France"}
|
1行に複数のステートメントを記述することは可能か?
セミコロン(;)を使用することで、1行に複数の文を記述することができます。
Python のシンプルなステートメント
Pythonのシンプルステートメントは、1行で構成されています。上で作成した複数行のステートメントも、1行で書けるので単純なステートメントと言えます。Pythonのシンプルステートメントの重要な種類を見てみましょう。
1. 表現方法
i = int("10")
sum = 1 + 2 + 3
|
2. 課題文
count = 10
message = "Hi"
|
3. Assertステートメント
assert 5 < 10
assert (True or False)
|
4. パスステートメント
5. del Statement
6. リターンステートメント
7.イールドステートメント
def yield_statement():
yield 'Statement 1'
|
8. raise ステートメント
def raise_example():
raise TypeError('Exception Example')
|
9. ブレークステートメント
numbers = [1, 2, 3]
for num in numbers:
if num > 2:
break
|
10. Continue Statement
numbers = [1, 2, 3]
for num in numbers:
if num > 2:
continue
print(num)
|
11. インポートステートメント
import collections
import calendar as cal
from csv import DictReader
|
12. グローバルステートメント
name = "Python"
def global_example():
global name
name = "Flask"
print(name)
global_example()
print(name)
|
13. 非局所ステートメント
def outer_function():
scope = "local"
def inner_function():
nonlocal scope
scope = "nonlocal"
print(scope)
inner_function()
print(scope)
outer_function()
|
Python の複合ステートメント
Pythonの複合ステートメントは、他のステートメントのグループを含み、それらの実行に影響を与えます。複合文は一般的に複数の行にまたがります。いくつかの複合文について簡単に見てみましょう。
1. if文
if 5 < 10:
print("This will always print")
else:
print("Unreachable Code")
|
2.ステートメントについて
for n in (1, 2, 3):
print(n)
|
3. whileステートメント
count = 5
while count > 0:
print(count)
count -= 1
|
4. tryステートメント
try:
print("try")
except ValueError as ve:
print(ve)
|
5.ステートメント付き
with open('data.csv') as file:
file.read()
|
6. 関数定義文
Python の関数定義は、実行可能なステートメントです。その実行により、現在のローカル名前空間における関数名が関数オブジェクトにバインドされます。この関数は、呼び出されたときだけ実行されます。
7. クラス定義文
実行可能なステートメントです。クラス定義では、クラスオブジェクトを定義します。
8. コルーチン関数定義書
import asyncio
async def ping(url):
print(f'Ping Started for {url}')
await asyncio.sleep(1)
print(f'Ping Finished for {url}')
|
結論
Pythonのステートメントは、Pythonインタプリタがコードを実行するために使用されます。Pythonのステートメントの種類について知っておくとよいでしょう。
References