Loops (for & while)


Loops (for & while)


ループが必要


リストの要素だけを出力したい場合は、以前に学んだ内容で効率的にコードを記述するのは難しいです.
次の例のように...2億個の構成部品を出力するには、非常に困難な作業になります.
squad = ['Leno', 'Tierny', 'Partey', 'Saka', 'Rowe', 'Pepe']

print(squad[0])
print(squad[1])
print(squad[2])
print(squad[3])
print(squad[4])
print(squad[5])

# Output: Leno
# Output: Tierny
# Output: Partey
# Output: Saka
# Output: Rowe
# Output: Pepe

For Loops: Introduction

forforループにより、特定のオブジェクトの要素に1つずつアクセスできます.
for <temporary variable> in <collection>:
  <action>
1)for→for loop実行文
2)<temporary variable>→現在のforループが実行されているオブジェクトに設定された一時変数
3)in<temporary variable><collection>を分離する目的
4)<collection>→loop overのリスト、チュートリアル、文字列など
5)<action>→loopの要素をとる行為
squad = ['Leno', 'Tierny', 'Partey', 'Saka', 'Rowe', 'Pepe']

for arsenal_player in squad:
    print(arsenal_player)

# Output: Leno
# Output: Tierny
# Output: Partey
# Output: Saka
# Output: Rowe
# Output: Pepe

Loop Control: Break

breakPythonの繰り返し文(forまたはwhile)から終了する際に使用されるキーワード(無限ループ防止用)
squad = ['Leno', 'Tierny', 'Partey', 'Saka', 'Rowe', 'Pepe']

print('Let me find the player you are looking for')

for player in squad:
    if player == 'Saka':
        print('He\'s in the training camp now!')
        break

# Output: Let me find the player you are looking for
# Output: He's in the training camp now!

# break 존재 → 실행 O, Saka 발견 이후 실행 중지
# break 삭제 → 실행 O, Saka 발견 이후 뒤에 있는 Rowe, Pepe까지 탐색 

Loop Control: Continue

continue次のサイクルに移動
# continue가 있을 때

number_list = [1, -5, 8, -2, 11, -25]

for number in number_list:
    if number < 0:
        print(number)
        continue
    print('plus')

# Output: plus
# Output: -5
# Output: plus
# Output: -2
# Output: plus
# Output: -25

# 변수 number이 음수일때 변수를 출력하고, continue가 있기에 다음 loop로 넘어감
# 여기선 다음 loop가 없으므로, number이 음수일때에는 'plus' 출력을 안함
# continue가 없을 때

number_list = [1, -5, 8, -2, 11, -25]

for number in number_list:
    if number < 0:
        print(number)
    print('plus')

# Output: plus
# Output: -5
# Output: plus
# Output: plus
# Output: -2
# Output: plus
# Output: plus
# Output: -25
# Output: plus

# 변수 number가 음수일때 변수를 출력하고, continue가 없기에 바로 'plus' 출력

For Loops: Using Range

for i in range(first_value, end_value, step) forおよびrange()を使用して整数範囲を表し、範囲の数で出力することができる<temporary variable>自体を印刷することもできます.<temporary variable>を一時変数として予め設定した変数を用いてもよい.range~stepを用いて元素間の間隔を決定することもできるstepは負数として指定してもよいし、逆にしてもよい
# step > 0 일 때

def for_loops():
    my_list = []
    for i in range(1, 10, 2):
      my_list.append(i)

    return my_list
 
 
 # Output
 [1, 3, 5, 7, 9]

 
  
 # step < 0 일 때
 
 def list_for_loops():
    my_list = []
    for i in range(9, 0, -2):
      my_list.append(i)
    
    return my_list
    
    
 # Output
 [9, 7, 5, 3, 1]
以下の例もある
for n in range(3):
    print(n)

# Output: 0
# Output: 1
# Output: 2

# 임시변수 n을 정수범위 0~2까지 설정
for back_number in range(5):
    print("Today, Number " + str(back_number + 1) + " will play.")

# Output: Today, Number 1 will play.
# Output: Today, Number 2 will play.
# Output: Today, Number 3 will play.
# Output: Today, Number 4 will play.
# Output: Today, Number 5 will play.

# 임시변수 back_number을 정수범위 0~4까지 설정
comment = "Play hard!"

for temp in range(3):
    print(comment)

# Output: Play hard!
# Output: Play hard!
# Output: Play hard!

While Loops: Introduction

while特定の条件が満たされた場合のみ実行
while <conditional statement>:
  <action>
1)while→while loopを実行する文
2)<conditional statement>→使用する条件
3)<action>→loopの要素をとる行為

次の例を示します.
number = 0
while number <= 3:
    print('You can play today, number ' + str(number + 1) + '.')
    number += 1
print('Sorry we are full now')

# Output: You can play today, number 1.
# Output: You can play today, number 2.
# Output: You can play today, number 3.
# Output: You can play today, number 4.
# Output: Sorry we are full now
1)0から
2)numberが3を下回る場合の運転条件(最初の文出力)
3)number += 1(以降、numberを1つずつ増やし、whileを再実行する)
4)while文運転終了後、2番目の文を出力

Take Away


まだ長い道があるようなwhileゲート

whileゲートが大体どのように動いているのか理解できます.
しかし、私にとって、非常に直感的なforゲートに比べて、whileゲートが頭の中で駆動する論理はまだ正確ではありません.
私たちはできるだけ多く書いて理解すべきだと思います.
リファレンス
https://www.w3schools.com/python/python_while_loops.asp