-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10_loops_tutorial.py
More file actions
211 lines (159 loc) · 4.41 KB
/
10_loops_tutorial.py
File metadata and controls
211 lines (159 loc) · 4.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# ========== FOR LOOP ==========
# 1. Basic for loop (over a list)
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"Fruit: {fruit}")
# 2. For loop with range()
# range(stop) - from 0 to stop-1
for i in range(5):
print(f"i = {i}") # 0, 1, 2, 3, 4
# range(start, stop) - from start to stop-1
for i in range(2, 6):
print(f"i = {i}") # 2, 3, 4, 5
# range(start, stop, step) - with step
for i in range(0, 10, 2):
print(f"i = {i}") # 0, 2, 4, 6, 8
# In reverse order
for i in range(10, 0, -1):
print(f"i = {i}") # 10, 9, 8, ..., 1
# 3. For loop with enumerate() (getting index and value)
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# With specified starting index
for index, fruit in enumerate(fruits, start=1):
print(f"#{index}: {fruit}")
# 4. For loop over a dictionary
person = {"name": "Pavel", "age": 25, "city": "Moscow"}
# By keys (default)
for key in person:
print(f"{key}: {person[key]}")
# By key-value pairs (recommended!)
for key, value in person.items():
print(f"{key}: {value}")
# Only by values
for value in person.values():
print(value)
# Only by keys (explicitly)
for key in person.keys():
print(key)
# 5. For loop over a string
text = "Python"
for char in text:
print(f"Character: {char}")
# 6. Nested loops
for i in range(3):
for j in range(3):
print(f"i={i}, j={j}")
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
# 7. For loop with zip() (iterating over multiple lists simultaneously)
names = ["Pavel", "Ivan", "Maria"]
ages = [25, 30, 28]
cities = ["Moscow", "SPb", "Kazan"]
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age} years old, {city}")
# ========== WHILE LOOP ==========
# 8. Basic while loop
count = 0
while count < 5:
print(f"count = {count}")
count += 1
# 9. Infinite loop with break
count = 0
while True:
print(f"count = {count}")
count += 1
if count >= 5:
break # Exit the loop
# 10. While with input condition
# number = 0
# while number != 42:
# number = int(input("Enter a number (42 to exit): "))
# print(f"You entered: {number}")
# ========== LOOP CONTROL ==========
# 11. break - interrupt the loop
for i in range(10):
if i == 5:
print("Reached 5, exiting")
break
print(f"i = {i}")
# 12. continue - skip iteration
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(f"Odd number: {i}")
# 13. else in loops (executes if the loop finished WITHOUT break)
# With break
for i in range(5):
if i == 3:
print("Found 3, interrupting")
break
else:
print("Loop completed fully") # Will NOT execute
# Without break
for i in range(5):
pass
else:
print("Loop completed fully") # Will execute
# Practical application: element search
numbers = [1, 2, 3, 4, 5]
search = 3
for num in numbers:
if num == search:
print(f"Found {search}!")
break
else:
print(f"{search} not found")
# 14. pass - empty operation (placeholder)
for i in range(5):
pass # Do nothing (used as a temporary placeholder)
# ========== PRACTICAL EXAMPLES ==========
# 15. Sum of numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
# 16. Finding maximum
numbers = [3, 7, 2, 9, 1, 5]
max_num = numbers[0]
for num in numbers[1:]:
if num > max_num:
max_num = num
print(f"Maximum: {max_num}")
# 17. Counting even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
print(f"Even numbers: {even_count}")
# 18. Creating a new list based on the old one
numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
squared.append(num ** 2)
print(f"Squares: {squared}")
# 19. Nested lists (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each matrix row
# 20. Iteration with list modification (be careful!)
# Wrong: modifying list during iteration
numbers = [1, 2, 3, 4, 5]
# for num in numbers:
# if num % 2 == 0:
# numbers.remove(num) # May skip elements!
# Correct: create a copy or use list comprehension
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]
print(f"Odd: {numbers}")