Search
Duplicate

Loops

νƒœκ·Έ
반볡문
for
for 문은 definite iteration νƒ€μž…μ΄λ©°, ꡬ문은 μ•„λž˜μ™€ κ°™λ‹€.
for <temporary variable> in <collection> : <action>
Python
볡사
temporary vaiable 은 말 κ·ΈλŒ€λ‘œ μž„μ˜μ˜ 값이기 λ•Œλ¬Έμ— 미리 μ •μ˜λ˜μ–΄ 질 ν•„μš”κ°€ μ—†λ‹€. λ˜ν•œ print 문은 λ“€μ—¬μ“°κΈ°λ₯Ό ν•΄μ•Όν•˜λŠ”λ°, 이 λ•Œ 같은 μˆ˜μ€€μ˜ 듀여쓰기에 μžˆλŠ” λͺ¨λ“  μ½”λ“œκ°€ λ°˜λ³΅λ˜μ–΄ μ‹€ν–‰λœλ‹€. (λ“€μ—¬μ“°κΈ°λ₯Ό μžŠμ€κ²½μš° IndentationError λ°œμƒ)
Using Range
for 문을 μΌμ •νšŸμˆ˜λ§Œ λ°˜λ³΅ν•˜κ³  μ‹Άλ‹€λ©΄ μ•„λž˜μ™€ 같은 ꡬ문을 μ‚¬μš©ν•œλ‹€.
range(start, end, step)
start : start둜 μ‹œμž‘λ˜λŠ” μˆ«μžλΆ€ν„° λ¦¬ν„΄λ©λ‹ˆλ‹€.
end : endκ°€ ν¬ν•¨λ˜μ§€ μ•ŠλŠ” μˆ«μžκΉŒμ§€ λ¦¬ν„΄λ©λ‹ˆλ‹€.
step : 연속적인 μˆ«μžλ“€ 쀑에, step의 간격에 ν•΄λ‹Ήλ˜λŠ” μˆ«μžλ“€λ§Œ λ¦¬ν„΄λ©λ‹ˆλ‹€.
temporary variable
temp κ°€ μ‚¬μš©λœ 경우, μ΄λŠ” print λ¬Έμ—μ„œλ„ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€.
ν•˜μ§€λ§Œ loop body 에 μ“°μ—¬μ„œλŠ” μ•ˆλœλ‹€.
tempoarry variable κ³Ό λ°˜λ³΅ν•˜λ €λŠ” κ²ƒμ˜ λ³€μˆ˜λͺ…이 κ°™μœΌλ©΄ μ•ˆλœλ‹€.
While
while 문은 indefinite iteration 이닀. while 문은 주어진 쑰건이 참인 ν•œ, 계속 λ°˜λ³΅ν•œλ‹€.
while <conditional statement>: <action>
Python
볡사
while 문으둜 배열을 μ°¨λ‘€λŒ€λ‘œ 좜λ ₯ν•˜κ³  μ‹Άλ‹€λ©΄ μ–΄λ–»κ²Œ ν•΄μ•Όν• κΉŒ?
λ¨Όμ € λ°°μ—΄μ˜ 길이λ₯Ό μ•Œμ•„μ•Όν•  것이닀.
index λŠ” 0 λΆ€ν„° μ‹œμž‘ν•΄μ•Ό ν•˜λ―€λ‘œ, μ΄ˆκΈ°κ°’μ„ 0 으둜 μž‘μ•„μ€€λ‹€.
while 문의 쑰건은 index < length μ—¬μ•Ό ν•œλ‹€.
index 에 ν•΄λ‹Ήν•˜λŠ” 값을 좜λ ₯ν•œ ν›„μ—λŠ” index 의 값을 μ¦κ°€μ‹œμΌœμ•Ό ν•  것이닀.
이λ₯Ό μ’…ν•©ν•˜λ©΄ λ‹€μŒκ³Ό κ°™λ‹€.
length = len([λ°°μ—΄λͺ…]) index = 0 while index < length: print([λ°°μ—΄λͺ…][index]) index += 1
Python
볡사
break, continue
nested loop
이쀑 for 문을 μ˜λ―Έν•œλ‹€. μ•„λž˜μ˜ μ˜ˆμ‹œ μ½”λ“œλ‘œ 이둠을 λŒ€μ²΄ν•œλ‹€.
[예제 μ½”λ“œ]
project_teams = [["Ava", "Samantha", "James"], ["Lucille", "Zed"], ["Edgar", "Gabriel"]] # Loop through each sublist for team in project_teams: # Loop elements in each sublist for student in team: print(student)
Python
볡사
[κ²°κ³Ό]
Ava
Samantha
James
Lucille
Zed
Edgar
Gabriel
[예제 μ½”λ“œ]
sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]] scoops_sold = 0 for location in sales_data: print(location) for element in location: scoops_sold += element print(scoops_sold)
Python
볡사
[κ²°κ³Ό]
[12, 17, 22] [2, 10, 3] [5, 12, 13] 96
List Comprehensions
(1) new_list = [<expression> for <element> in <collection>]
[μ˜ˆμ‹œ μ½”λ“œ]
numbers = [2, -1, 79, 33, -45] doubled = [] for number in numbers: doubled.append(number * 2) print(doubled)
Python
볡사
[κ²°κ³Ό]
[4, -2, 158, 66, -90]
(2) new_list = [<expression> for <element> in <collection> if <쑰건>]
[μ˜ˆμ‹œ μ½”λ“œ]
numbers = [2, -1, 79, 33, -45] doubled = [num * 2 if num < 0 else num * 3 for num in numbers ] print(doubled)
Python
볡사
[κ²°κ³Ό]
[6, -2, 237, 99, -90]