본문 바로가기

Python

Python_G-005. Loop Type

Loop Type Description Example Output
For Loop Iterates over a sequence
(e.g., list, tuple, string)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# Output
apple
banana
cherry
While Loop Repeats as long as a condition is true count = 0
while count < 5:
    print(count)
    count += 1
# Output
0
1
2
3
4
Nested Loops Loop inside another loop numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
for number in numbers:
    for letter in letters:
        print(number, letter)
# Output
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
Break Terminates the loop for i in range(10):
    if i == 5:
        break
    print(i)
 # Output
0
1
2
3
4
Continue Skips the rest of the code inside the loop for the current iteration for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
# output
1
3
5
7
9
(if) Else

Executes a block of code once when the loop is not terminated by a break statement for i in range(3):
    print(i)
else:
    print("Finished loop")
# Output
0
1
2
Finished loop
for i in range(3):
    if i < 2:
        print(i)
    else:
        print("Finished loop")
# Output
0
1
Finished loop