整数に対する range() 関数を使ったチェック
このステップでは、Python の range()
関数を使って数値のシーケンスを生成し、整数がその範囲内にあるかどうかをチェックする方法を学びます。range()
関数は、数値のシーケンスを繰り返し処理する必要がある場合や、特定の区間内の整数のリストを作成する場合に特に便利です。
VS Code エディタを使って ~/project
ディレクトリに range_check.py
という名前の新しい Python スクリプトを作成しましょう。
#!/usr/bin/env python3
## Define a variable
number = 25
## Check if the number is within the range of 1 to 50 (exclusive)
if number in range(1, 50):
print(f"{number} is within the range of 1 to 49")
else:
print(f"{number} is outside the range of 1 to 49")
## Check if the number is within the range of 0 to 100 with a step of 5
if number in range(0, 101, 5):
print(f"{number} is within the range of 0 to 100 with a step of 5")
else:
print(f"{number} is outside the range of 0 to 100 with a step of 5")
このスクリプトでは、以下のことを行っています。
- 変数
number
を定義し、値 25 を代入しています。
range(1, 50)
関数を使って、1 から 50 まで(ただし 50 は含まない)の数値のシーケンスを生成しています。
in
演算子を使って、number
が生成されたシーケンス内に存在するかどうかをチェックしています。
range(0, 101, 5)
関数を使って、0 から 101 まで(ただし 101 は含まない)、ステップ幅 5 で数値のシーケンスを生成しています(つまり、0, 5, 10, 15, ..., 100)。
では、スクリプトを実行しましょう。
python ~/project/range_check.py
以下の出力が表示されるはずです。
25 is within the range of 1 to 49
25 is within the range of 0 to 100 with a step of 5
次に、スクリプトを変更して、number
の値を 7 に変更し、出力を観察しましょう。
#!/usr/bin/env python3
## Define a variable
number = 7
## Check if the number is within the range of 1 to 50 (exclusive)
if number in range(1, 50):
print(f"{number} is within the range of 1 to 49")
else:
print(f"{number} is outside the range of 1 to 49")
## Check if the number is within the range of 0 to 100 with a step of 5
if number in range(0, 101, 5):
print(f"{number} is within the range of 0 to 100 with a step of 5")
else:
print(f"{number} is outside the range of 0 to 100 with a step of 5")
スクリプトを実行します。
python ~/project/range_check.py
以下の出力が表示されるはずです。
7 is within the range of 1 to 49
7 is outside the range of 0 to 100 with a step of 5
これで、Python で range()
関数と in
演算子を使って、整数が特定の範囲内にあるかどうかをチェックする方法がわかりました。