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 |
'Python' 카테고리의 다른 글
Python_G-007. List vs Tuple vs set vs dictionary (0) | 2025.01.16 |
---|---|
Python_G-006. 10 Basic Plot (with Matplotlib) (0) | 2025.01.12 |
Python_G-004 : 10 basic operations & functions (0) | 2025.01.12 |
Python_G-003 : Variable Type (0) | 2025.01.12 |
Python_G-002 : 10 basic Libraries (0) | 2025.01.12 |