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]