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