0
0

Python学習3日目~for文~

Last updated at Posted at 2024-01-22

for文

繰り返し処理が出来る

example.py
for 変数 in イテラブル:
    ...

色んなイテラブルから要素を取り出すことができる

example.py
for x in 'Python':
    print(x)
実行結果
P
y
t
h
o
n

こんな感じで実は文字列でも要素を取り出せる(知らんかった)
リストやタプルから要素を取り出すとシンプルに要素がそのまま変数に入る。
辞書の場合は以下の通り

example.py
meat = {'beaf': 199,'chicken': 68,'pork': 138}
for x in meat:
    print(x)
実行結果
beaf
chicken
pork

値も出したいときは以下の通り

example.py
meat = {'beaf': 199,'chicken': 68,'pork': 138}
for x in meat:
    print(x,'is',meat[x],'yen')
実行結果
beaf is 199 yen
chicken is 68 yen
pork is 138 yen

itemsメソッドを使えばもっと簡単に取り出せる

example.py
meat = {'beaf': 199,'chicken': 68,'pork': 138}
for x in meat.items():
    print(x)
実行結果
('beaf',199)
('chicken',68)
('pork',138)

range関数

for文でn回繰り返したいときに使える

example.py
range(開始値,終了値,ステップ)

enumerate関数

何番目に取り出した要素なのかというのをわかりやすくしてくれる

example.py
for 変数A,変数B in enumerate(イテラブル,開始値):
    ...
example.py
lang = ['EN','JP','CH']
for i,x in enumerate(lang,1):
    print(i,x)
実行結果
1 EN
2 JP
3 CH

While文

for文と同じく繰り返し処理をする
for文の違いとしては式の値に応じて繰り返し処理を出来るところ

example.py
catalog = []
while len(catalog) < 3:
    item = input('item: ')
    catalog.append(item)
print('catalog:',catalog)
実行結果
item:apple
item:banana
item:coconut
catalog:['apple','banana','coconut']

continue文

continue文を使うとループ内部にある残りの文を実行せずに次のループに移行できる

example.py
catalog = []
while len(catalog) < 3:
    item = input('item: ')
    if item in catalog:
        print(item,'is on the catalog')
        continue
    catalog.append(item)
print('catalog:',catalog)
実行結果
item:apple
item:banana
item:banana
banana is on the catalog
item:coconut
catalog:['apple','banana','coconut']

break文

break文を使うとループ内部にある残りの文を実行せずにループ処理を終了する

example.py
catalog = []
while len(catalog) < 3:
    item = input('item: ')
    if item in catalog:
        print(item,'is on the catalog')
        break
    catalog.append(item)
print('catalog:',catalog)
実行結果
item:apple
item:banana
item:banana
banana is on the catalog
catalog:['apple','banana']

else節

ifの場合は条件がFalseの場合にelse内の処理がされる
while,for文の場合はbreak文で処理が終了しなかったときにelse内の処理が行われる

example.py
catalog = []
while len(catalog) < 3:
    item = input('item: ')
    if item in catalog:
        print(item,'is on the catalog')
        break
    catalog.append(item)
else:
    print('catalog:',catalog)
実行結果
item:apple
item:banana
item:banana
banana is on the catalog # リスト内が表示されない
実行結果
item:apple
item:banana
item:coconut
catalog:['apple','banana','coconut'] #リストが表示される
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