range() と for ループ
range() のようなイテラブルを使って for ループを使用できます:
for index in range(5):
print(f'Input the next number {index}:')
n = int(input())
print(f'Great! you've entered {n}')
| ユーザー入力 | プログラムの出力 |
|---|---|---|
0 | 7 | Input the next number 0: |
1 | 9 | Input the next number 1: |
2 | -4 | Input the next number 2: |
3 | 8 | Input the next number 3: |
4 | 0 | Input the next number 4: |
この例では、変数 index は最初に 0 の値を取り、for 文内のコードブロックが実行されました。その後、index は順に 1、2、3、そして最後に 4 の値を取りました。
for ループは range() と一緒に使われることが非常に多く、これからもその使い方を頻繁に見ていくことになります。
チャレンジ
ある数字から始まって0まで数えるカウントダウンを作成してください。
入力には1つの正の整数 n が含まれます。プログラムはカウントダウンのすべての数字を、各行に1つずつ出力する必要があります。
入力 | 出力 |
|---|---|
4 | 4 |
2 | 2 |
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB