-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloops.py
More file actions
64 lines (50 loc) · 1.81 KB
/
Copy pathloops.py
File metadata and controls
64 lines (50 loc) · 1.81 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
# ================================
# LOOP PLAYGROUND PROJECT
# Learn about: for loops, while loops, if, break, continue, else with loops
# ================================
print("=== FOR LOOP EXAMPLE ===")
# A for loop repeats a block of code for each item in a sequence (like a list or range).
for i in range(5): # range(5) generates numbers: 0,1,2,3,4
print("Iteration:", i)
print("\n=== WHILE LOOP EXAMPLE ===")
# A while loop keeps repeating as long as its condition is True.
counter = 0
while counter < 5: # keep looping until counter reaches 5
print("Counter is:", counter)
counter += 1 # increment counter to avoid infinite loop
print("\n=== IF STATEMENT INSIDE LOOP ===")
# We can use if inside loops to make decisions.
for num in range(1, 6):
if num % 2 == 0: # check if number is even
print(num, "is even")
else: # otherwise, it's odd
print(num, "is odd")
print("\n=== BREAK STATEMENT ===")
# 'break' immediately stops the loop
for num in range(1, 10):
if num == 5:
print("Reached 5, breaking the loop.")
break # stop loop completely
print("Number:", num)
print("\n=== CONTINUE STATEMENT ===")
# 'continue' skips the current iteration and goes to the next one
for num in range(1, 6):
if num == 3:
print("Skipping 3")
continue # skip printing 3
print("Number:", num)
print("\n=== ELSE WITH LOOP ===")
# Loops can have an 'else' block that runs if the loop finishes normally (no break).
for num in range(1, 4):
print("Number:", num)
else:
print("Loop finished without break!")
print("\n=== ELSE WITH BREAK ===")
# If a break happens, the else block will NOT run.
for num in range(1, 6):
if num == 3:
print("Breaking at 3")
break
print("Number:", num)
else:
print("This will not print because of break.")