0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

for文

Last updated at Posted at 2021-04-05

for文

リストの要素をすべて出力したい場合、

 例: fruits = ['apple','banana','orange'] 
 print('好きな果物は'+fruits[0]+'です')  ※print(f"好きな果物は{fruits[0]}です") と記述しても出力できます
 print('好きな果物は'+fruits[1]+'です')
 print('好きな果物は'+fruits[2]+'です')

と記述すればapple,banana,orangeが出力できるが、同じ記述を何回も書くのは工数がかかります。
その際に、for文を用いると、簡単に記述することができます。
記述はfor 変数名 in リスト: と記述することで、リストの要素の数だけ処理を繰り返す事ができます。

例: fruits = ['apple','banana','orange']
  for fruit in fruits:
      print('好きな果物は'+fruit+'です') ※ここでも、print(f"好きな果物は{fruit}です")と記述しても出力できます

と記述することで、同様にapple,banana,orangeが出力できます。

これはfruitという変数の中に、リストの要素が先頭から順に1つずつ入っていき、その上でfor文の処理が実行されます。処理はリストの要素の数だけ繰り返されます。(変数名は自由ですが、リストの単数形にすることが慣習的に多い)

for文の流れ

①変数fruitに'apple'が代入され、for文の処理が実行される

②変数fruitに'banana'が代入され、for文の処理が実行される

③変数fruitに'orange'が代入され、for文の処理が実行される

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?