Skip to content

Commit ba238cf

Browse files
committed
Add example: Loop variable resilient to changes
Closes satwikkansal#11
1 parent 1a79352 commit ba238cf

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1407,6 +1407,36 @@ tuple()
14071407

14081408
---
14091409

1410+
### Loop variable resilient to changes
1411+
1412+
Suggested by @tukkek in [this](https://github.com/satwikkansal/wtfPython/issues/11) issue.
1413+
1414+
```py
1415+
for i in range(7):
1416+
print(i)
1417+
i = 10
1418+
```
1419+
1420+
**Output:**
1421+
```
1422+
0
1423+
1
1424+
2
1425+
3
1426+
4
1427+
5
1428+
6
1429+
```
1430+
1431+
Did you expect the loop to run just once?
1432+
1433+
#### 💡 Explanation:
1434+
1435+
- [Source](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement)
1436+
- The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(7)` this case) is unpacked and assigned the target list variables (`i` in this case).
1437+
1438+
---
1439+
14101440
### Let's see if you can guess this?
14111441

14121442
Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.

0 commit comments

Comments
 (0)