1
1

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 42. for文とbreak文とcontinue文

Last updated at Posted at 2020-03-09

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■for文

◆for文の基本

一度for文を使わず、while文を使って例を出してみる。

while
some_list = [1, 2, 3, 4, 5]

i = 0

# i < some_listに含まれているデータの個数 の間はループ
while i < len(some_list):
    # iをインデックスとするsome_listの要素をprint
    print(some_list[i])
    i += 1
result
1
2
3
4
5

これをfor文を使って記述すると、以下のようになる。

for
some_list = [1, 2, 3, 4, 5]

for i in some_list:
    print(i)
result
1
2
3
4
5

このコードでは、some_listに含まれている要素を1つずつiに代入する反復を行っている。
このように、反復処理を行うときにfor文は有効。
もちろんfor文にもbreakcontinueは使える。

◆他の例1
for
for s in 'abcde':
    print(s)
result
a
b
c
d
e
◆他の例2
for
for word in ['My', 'name', 'is', 'Tony']:
    print(word)
result
My
name
is
Tony
1
1
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
1
1