0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python基礎】for文を使った繰り返し処理

Last updated at Posted at 2023-12-25

for文とは、繰り返し処理に使用する構文のことです。

for 変数 in リスト:
    処理

記載例

hoge_list = [1, 2, 3]
for i in hoge_list:
    print(i)
    
> 1
> 2
> 3

 

  • 繰り返し処理時、インデックス番号を取得
hoge_list = ["A", "B", "C"]
# 「1」の部分に記載した数からカウントされる(記載しない場合、0から)
# countにインデックス番号、iに要素が入る
for count, i in enumerate(hoge_list, 1):
   print(f"{count}番目: {i}")

> 1番目: A
> 2番目: B
> 3番目: C

 

  • 次の要素にスキップする場合
hoge_list = [1, 2, 3]
for i in hoge_list:
    if i == 2:
        continue
    print(i)
    
> 1
> 3

 

  • 繰り返し処理を中断する
hoge_list = [1, 2, 3]
for i in hoge_list:
    if i == 2:
        break
    print(i)
    
> 1
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?