-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloops.py
More file actions
465 lines (368 loc) · 11.6 KB
/
Copy pathloops.py
File metadata and controls
465 lines (368 loc) · 11.6 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
"""
Module: loops.py
Topic: Loops in Python
Level: Beginner
This file teaches you about:
- for loops
- while loops
- range() function
- enumerate() function
- zip() function
- Nested loops
- Loop else clause
"""
# =============================================================================
# SECTION 1: FOR LOOPS - BASICS
# =============================================================================
print("=" * 60)
print("FOR LOOPS - BASICS")
print("=" * 60)
# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
print("Iterating over a list:")
for fruit in fruits:
print(f" I like {fruit}")
# Iterating over a string
print("\nIterating over a string:")
for char in "Python":
print(f" Character: {char}")
# Iterating over a dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'NYC'}
print("\nIterating over dictionary keys:")
for key in person:
print(f" {key}")
print("\nIterating over dictionary values:")
for value in person.values():
print(f" {value}")
print("\nIterating over dictionary items:")
for key, value in person.items():
print(f" {key}: {value}")
# =============================================================================
# SECTION 2: RANGE FUNCTION
# =============================================================================
print("\n" + "=" * 60)
print("RANGE FUNCTION")
print("=" * 60)
# range(stop) - 0 to stop-1
print("range(5):")
for i in range(5):
print(f" {i}", end="")
print()
# range(start, stop) - start to stop-1
print("\nrange(2, 7):")
for i in range(2, 7):
print(f" {i}", end="")
print()
# range(start, stop, step) - with step
print("\nrange(0, 10, 2):")
for i in range(0, 10, 2):
print(f" {i}", end="")
print()
# Negative step
print("\nrange(10, 0, -1):")
for i in range(10, 0, -1):
print(f" {i}", end="")
print()
# Converting range to list
numbers = list(range(5))
print(f"\nlist(range(5)): {numbers}")
# Using range with len()
words = ['hello', 'world', 'python']
print("\nUsing range with len():")
for i in range(len(words)):
print(f" Index {i}: {words[i]}")
# =============================================================================
# SECTION 3: ENUMERATE FUNCTION
# =============================================================================
print("\n" + "=" * 60)
print("ENUMERATE FUNCTION")
print("=" * 60)
# enumerate() returns index and value
fruits = ['apple', 'banana', 'cherry']
print("enumerate(fruits):")
for index, fruit in enumerate(fruits):
print(f" {index}: {fruit}")
# Starting index from a different number
print("\nenumerate(fruits, start=1):")
for index, fruit in enumerate(fruits, start=1):
print(f" {index}: {fruit}")
# Getting pairs
print("\nGetting index-value pairs:")
for pair in enumerate(fruits):
print(f" {pair}")
# =============================================================================
# SECTION 4: ZIP FUNCTION
# =============================================================================
print("\n" + "=" * 60)
print("ZIP FUNCTION")
print("=" * 60)
# zip() combines multiple iterables
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['NYC', 'LA', 'Chicago']
print("Combining with zip:")
for name, age, city in zip(names, ages, cities):
print(f" {name}, {age}, {city}")
# Creating a dictionary from two lists
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'NYC']
person = dict(zip(keys, values))
print(f"\nDictionary from zip: {person}")
# zip with different length iterables
short = [1, 2, 3]
long = ['a', 'b', 'c', 'd', 'e']
print(f"\nzip stops at shortest:")
for num, letter in zip(short, long):
print(f" {num}: {letter}")
# zip_longest from itertools
from itertools import zip_longest
print(f"\nzip_longest fills missing with None:")
for num, letter in zip_longest(short, long, fillvalue='N/A'):
print(f" {num}: {letter}")
# =============================================================================
# SECTION 5: WHILE LOOPS
# =============================================================================
print("\n" + "=" * 60)
print("WHILE LOOPS")
print("=" * 60)
# Basic while loop
count = 0
print("Counting with while:")
while count < 5:
print(f" Count: {count}")
count += 1
# While loop with user input simulation
print("\nSimulating user input:")
response = ""
attempts = 0
responses = ['', '', 'quit']
while response != 'quit' and attempts < 3:
response = responses[attempts]
print(f" Attempt {attempts + 1}: response = '{response}'")
attempts += 1
print(" Loop ended")
# While loop with condition
print("\nFinding first number > 100 divisible by 7:")
number = 101
while number % 7 != 0:
number += 1
print(f" Found: {number}")
# =============================================================================
# SECTION 6: LOOP ELSE CLAUSE
# =============================================================================
print("\n" + "=" * 60)
print("LOOP ELSE CLAUSE")
print("=" * 60)
# Else runs if loop completes without break
numbers = [1, 3, 5, 7, 9]
target = 4
print(f"Searching for {target} in {numbers}:")
for num in numbers:
if num == target:
print(f" Found {target}!")
break
else:
print(f" {target} not found in the list")
# Another example
print("\nChecking if all numbers are positive:")
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num < 0:
print(" Found negative number!")
break
else:
print(" All numbers are positive!")
# While with else
print("\nWhile with else:")
count = 0
while count < 3:
print(f" Count: {count}")
count += 1
else:
print(" Loop completed normally")
# =============================================================================
# SECTION 7: NESTED LOOPS
# =============================================================================
print("\n" + "=" * 60)
print("NESTED LOOPS")
print("=" * 60)
# Nested for loops
print("Multiplication table:")
for i in range(1, 4):
for j in range(1, 4):
product = i * j
print(f" {i} × {j} = {product}")
print()
# Processing nested structures
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Processing a matrix:")
for row_idx, row in enumerate(matrix):
for col_idx, value in enumerate(row):
print(f" matrix[{row_idx}][{col_idx}] = {value}")
# Pattern printing
print("\nPrinting a pattern:")
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
# =============================================================================
# SECTION 8: ITERATING OVER COMPLEX STRUCTURES
# =============================================================================
print("\n" + "=" * 60)
print("ITERATING OVER COMPLEX STRUCTURES")
print("=" * 60)
# Dictionary of lists
students = {
'Alice': [85, 90, 78],
'Bob': [92, 88, 95],
'Charlie': [75, 82, 80]
}
print("Student grades:")
for name, grades in students.items():
average = sum(grades) / len(grades)
print(f" {name}: grades={grades}, average={average:.1f}")
# List of dictionaries
employees = [
{'name': 'Alice', 'department': 'Engineering', 'salary': 80000},
{'name': 'Bob', 'department': 'Marketing', 'salary': 65000},
{'name': 'Charlie', 'department': 'Engineering', 'salary': 90000}
]
print("\nEmployees by department:")
departments = {}
for emp in employees:
dept = emp['department']
if dept not in departments:
departments[dept] = []
departments[dept].append(emp['name'])
for dept, names in departments.items():
print(f" {dept}: {names}")
# =============================================================================
# SECTION 9: ITERATING WITH ITEMS
# =============================================================================
print("\n" + "=" * 60)
print("ITERATING WITH ITEMS() AND DICT METHODS")
print("=" * 60)
# Safe iteration over dictionary
prices = {'apple': 0.5, 'banana': 0.3, 'orange': 0.8}
print("Calculating totals:")
quantities = {'apple': 3, 'banana': 5, 'grape': 2}
for item, price in prices.items():
if item in quantities:
total = price * quantities[item]
print(f" {item}: {quantities[item]} × ${price} = ${total:.2f}")
else:
print(f" {item}: not in cart")
# Using get() for safe access
print("\nUsing get() for safe access:")
for item, qty in quantities.items():
price = prices.get(item, 0)
if price:
print(f" {item}: {qty} × ${price} = ${qty * price:.2f}")
else:
print(f" {item}: price not found")
# =============================================================================
# SECTION 10: PRACTICAL EXAMPLES
# =============================================================================
print("\n" + "=" * 60)
print("PRACTICAL EXAMPLES")
print("=" * 60)
def find_primes(limit):
"""Find all prime numbers up to limit."""
primes = []
for num in range(2, limit + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes
print("\nPrime numbers up to 30:")
print(f" {find_primes(30)}")
def fibonacci_sequence(n):
"""Generate Fibonacci sequence with n terms."""
if n <= 0:
return []
if n == 1:
return [0]
fib = [0, 1]
while len(fib) < n:
fib.append(fib[-1] + fib[-2])
return fib
print(f"\nFibonacci sequence (10 terms):")
print(f" {fibonacci_sequence(10)}")
def calculate_factorial(n):
"""Calculate factorial using a loop."""
if n < 0:
return None
result = 1
for i in range(1, n + 1):
result *= i
return result
print(f"\nFactorials:")
for i in range(6):
print(f" {i}! = {calculate_factorial(i)}")
def word_frequency(text):
"""Count word frequency in text."""
words = text.lower().split()
frequency = {}
for word in words:
# Remove punctuation
word = ''.join(c for c in word if c.isalnum())
if word:
frequency[word] = frequency.get(word, 0) + 1
return frequency
sample = "The quick brown fox jumps over the lazy dog. The dog was not impressed."
print(f"\nWord frequency:")
freq = word_frequency(sample)
for word, count in sorted(freq.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" '{word}': {count}")
def simulate_game():
"""Simulate a simple game with while loop."""
position = 0
moves = 0
max_moves = 20
# Simulated dice rolls
rolls = [3, 4, 6, 2, 5, 1, 4, 3]
print("\nGame simulation:")
while position < 20 and moves < max_moves:
roll = rolls[moves % len(rolls)]
position += roll
moves += 1
print(f" Move {moves}: rolled {roll}, position = {position}")
if position >= 20:
print(f" Won in {moves} moves!")
else:
print(f" Game over after {max_moves} moves")
simulate_game()
def transpose_matrix(matrix):
"""Transpose a matrix using nested loops."""
if not matrix:
return []
rows = len(matrix)
cols = len(matrix[0])
# Create empty transposed matrix
transposed = []
for j in range(cols):
new_row = []
for i in range(rows):
new_row.append(matrix[i][j])
transposed.append(new_row)
return transposed
matrix = [[1, 2, 3], [4, 5, 6]]
print(f"\nMatrix transposition:")
print(f" Original: {matrix}")
print(f" Transposed: {transpose_matrix(matrix)}")
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
print("\n" + "=" * 60)
print("✅ You've learned about loops!")
print("📚 Next: Learn about loop control in loop_control.py")
print("=" * 60)