Skip to content

Commit 5eaa985

Browse files
committed
Add exercises and explanations for Python iteration concepts in BTS
1 parent 4ab8d72 commit 5eaa985

10 files changed

+479
-0
lines changed

β€Ž10_loops/10_loops.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#Question No 1.
2+
numbers = [1,-2,-3,-4,5,6,-7,-8,9,10]
3+
4+
positive_number_count = 0
5+
for num in numbers:
6+
if num > 0:
7+
positive_number_count+=1
8+
print("Final count of positive number is :" , positive_number_count) #6
9+
10+
#Question No 2.
11+
n = 10
12+
sum_even = 0
13+
for i in range(1,n+1):
14+
if i % 2 == 0:
15+
sum_even+=1
16+
print("Sum of even number is:",sum_even)
17+
18+
#Question No 3.
19+
20+
number = 3
21+
22+
for i in range(1,11):
23+
if i == 5:
24+
continue
25+
print(number , "x", i , '=', number*i)
26+
27+
#Question No 4.
28+
29+
input_str = "Python"
30+
31+
reversed_str = ""
32+
for char in input_str:
33+
reversed_str = char + reversed_str
34+
35+
print(reversed_str)
36+
37+
38+
#Question No 5.
39+
input_str = "teeter"
40+
41+
for char in input_str:
42+
print(char)
43+
if input_str.count(char) == 1:
44+
print("char is :", char)
45+
break
46+
47+
#Question No 6.
48+
number = 5
49+
factorial = 1
50+
51+
while number > 0:
52+
factorial = factorial * number
53+
number = number -1
54+
55+
print("Factorial is :", factorial)
56+
57+
#Question No 7.
58+
59+
while True:
60+
number = int(input("Enter value b/w 1 and 10 "))
61+
if 1 <= number <=10:
62+
print("thanks")
63+
break
64+
else:
65+
print("invalid number please again Enter")
66+
67+
68+
#Question No 8.
69+
number = 29
70+
is_prime = True
71+
72+
if number > 1:
73+
for i in range(2, number):
74+
if (number % i) == 0:
75+
is_prime = False
76+
break
77+
78+
print(is_prime)
79+
80+
81+
#Question No 9.
82+
83+
items = ["apple" , "banana" , "ornage" , "apple" , "mango"]
84+
unique_item = set()
85+
86+
for item in items:
87+
if item in unique_item:
88+
print("Duplicate")
89+
break
90+
unique_item.add(item)
91+
92+
print(unique_item)
93+
#Question No 10.
94+
95+
96+
import time
97+
98+
wait_time = 1
99+
max_retries = 5
100+
attempts = 0
101+
102+
while attempts < max_retries:
103+
print("Attempt", attempts + 1 , " wait time" , wait_time)
104+
time.sleep(wait_time)
105+
wait_time*=2
106+
attempts+=1
107+

β€Žbts_in_loops/instructions.md

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
````
2+
🧠 PYTHON ITERATION β€” BEHIND THE SCENES (BTS)
3+
============================================
4+
5+
🎯 PURPOSE:
6+
------------
7+
Understand how Python loops (like `for`) work behind the scenes using:
8+
- iter()
9+
- next()
10+
- Iterable and Iterator concepts
11+
12+
This helps write better loops, understand errors like StopIteration, and even build your own custom iterators!
13+
14+
────────────────────────────────────────────
15+
1️⃣ ITERATION TOOLS β€” WHAT WE USE TO LOOP
16+
────────────────────────────────────────────
17+
These are tools used to iterate in Python:
18+
19+
- for loops
20+
- list/set/dict comprehensions
21+
- while loops using manual next()
22+
- generator expressions
23+
24+
All these tools work on top of **iterable** objects.
25+
26+
────────────────────────────────────────────
27+
2️⃣ ITERABLE OBJECTS β€” WHAT WE LOOP OVER
28+
────────────────────────────────────────────
29+
An object is **iterable** if it can return items one at a time.
30+
31+
Examples of iterable objects:
32+
- list β†’ [1, 2, 3]
33+
- string β†’ "hello"
34+
- tuple β†’ (1, 2, 3)
35+
- set, dict, file objects
36+
37+
Technically, they must define a method:
38+
```python
39+
__iter__()
40+
````
41+
42+
This method returns an **iterator** object.
43+
44+
────────────────────────────────────────────
45+
3️⃣ ITERATORS β€” WHO DOES THE REAL WORK
46+
────────────────────────────────────────────
47+
An iterator is an object that:
48+
49+
βœ… Has a method `__iter__()` β†’ returns itself
50+
βœ… Has a method `__next__()` β†’ returns the next item
51+
🚫 Raises `StopIteration` when all items are used
52+
53+
Example:
54+
55+
```python
56+
lst = [1, 2, 3]
57+
itr = iter(lst)
58+
59+
print(next(itr)) # 1
60+
print(next(itr)) # 2
61+
print(next(itr)) # 3
62+
print(next(itr)) # StopIteration Error
63+
```
64+
65+
────────────────────────────────────────────
66+
4️⃣ HOW FOR LOOPS WORK INTERNALLY
67+
────────────────────────────────────────────
68+
Code you write:
69+
70+
```python
71+
for item in myList:
72+
print(item)
73+
```
74+
75+
Python translates it behind the scenes to:
76+
77+
```python
78+
itr = iter(myList)
79+
while True:
80+
try:
81+
item = next(itr)
82+
print(item)
83+
except StopIteration:
84+
break
85+
```
86+
87+
πŸ” So `for` = `iter()` + repeated `next()`
88+
89+
────────────────────────────────────────────
90+
5️⃣ ITERABLE vs ITERATOR β€” WHAT’S THE DIFFERENCE?
91+
────────────────────────────────────────────
92+
93+
| Feature | Iterable | Iterator |
94+
| ------------------ | -------- | -------- |
95+
| Has **iter** | βœ… | βœ… |
96+
| Has **next** | ❌ | βœ… |
97+
| Remembers position | ❌ | βœ… |
98+
99+
Check using:
100+
101+
```python
102+
from collections.abc import Iterable, Iterator
103+
104+
print(isinstance([1,2,3], Iterable)) # True
105+
print(isinstance([1,2,3], Iterator)) # False
106+
107+
print(isinstance(iter([1,2,3]), Iterator)) # True
108+
```
109+
110+
⚠️ `iter(myList) is myList` β†’ False
111+
Because `iter()` returns a **new** iterator object.
112+
113+
────────────────────────────────────────────
114+
6️⃣ REAL-LIFE ANALOGY 🎧
115+
────────────────────────────────────────────
116+
Iterable = Playlist β†’ You can restart anytime
117+
Iterator = Music Player β†’ It plays one by one and remembers which song is playing
118+
119+
────────────────────────────────────────────
120+
7️⃣ FILE OBJECTS ARE ITERATORS πŸ“‚
121+
────────────────────────────────────────────
122+
You can loop through files directly:
123+
124+
```python
125+
with open("file.txt") as f:
126+
for line in f:
127+
print(line)
128+
```
129+
130+
Why? Because file objects implement both `__iter__()` and `__next__()`.
131+
132+
────────────────────────────────────────────
133+
8️⃣ CREATING CUSTOM ITERATORS πŸ› οΈ
134+
────────────────────────────────────────────
135+
You can build your own iterator class using `__iter__()` and `__next__()`:
136+
137+
Example:
138+
139+
```python
140+
class CountUpto:
141+
def __init__(self, max):
142+
self.max = max
143+
self.current = 1
144+
145+
def __iter__(self):
146+
return self
147+
148+
def __next__(self):
149+
if self.current > self.max:
150+
raise StopIteration
151+
val = self.current
152+
self.current += 1
153+
return val
154+
155+
# Usage
156+
for num in CountUpto(3):
157+
print(num) # 1, 2, 3
158+
```
159+
160+
────────────────────────────────────────────
161+
9️⃣ SUMMARY β€” KEY TAKEAWAYS βœ…
162+
────────────────────────────────────────────
163+
164+
- `for` loops use `iter()` to get an iterator, and `next()` to get each value.
165+
- `StopIteration` tells Python when to stop.
166+
- Iterables (like list, str, file) do not have memory of position.
167+
- Iterators remember where they left off.
168+
- File objects are their own iterators.
169+
- You can build custom iterators using Python classes.
170+
171+
────────────────────────────────────────────
172+
πŸ”Ÿ PRACTICE QUESTIONS πŸ’¬
173+
────────────────────────────────────────────
174+
175+
1. What does `iter()` return?
176+
2. Why is `iter(myList) is myList` False?
177+
3. What happens if we keep calling `next()` after the last item?
178+
4. What exception tells Python to stop a loop?
179+
5. What's the difference between an iterable and an iterator?
180+
181+
🎯 Tip: Mastering this helps you understand how loops, generators, comprehensions, and file I/O work at a deeper level!
182+
183+
```
184+
185+
---
186+
187+
Would you also like a **printable PDF version**, a **diagram**, or a **Roman Urdu explanation** for revision?
188+
```

0 commit comments

Comments
Β (0)