Skip to content

Commit ce29ad0

Browse files
author
aryan
committed
Added more content
1 parent ea69080 commit ce29ad0

13 files changed

Lines changed: 875 additions & 9 deletions

File tree

content/notes/iit-madras/data-science-and-application/foundational-level/python/_index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
---
22
title: Programming in Python 🐍
3+
type: cards
34
date: 2025-05-08
45
tags:
56
- Notes
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
title: Tutorial on for loop and difference between while loop and for loop
3+
date: 2025-05-08
4+
tags:
5+
- Notes
6+
- IIT Madras
7+
excludeSearch: false
8+
weight: 40
9+
---
10+
11+
Right, let's break down the `for` loop and how it's different from the `while` loop, using the information from the sources you provided! 😊
12+
13+
**What is a `for` loop?**
14+
15+
Just like `while` loops, `for` loops are used to make your computer **repeat actions**. They are considered very powerful. Programming is all about doing complex things quickly and easily, and loops are key to that!
16+
17+
The `for` loop is Python's tool for **iterating** over sequences or executing a block of code multiple times. The general format involves a header line ending in a colon `:`, followed by an indented block of statements that get repeated. Indentation is super important here.
18+
19+
There are two main ways the sources show `for` loops being used:
20+
21+
1. **Using `for` with `range()`** 🔢
22+
This is a very common pattern, especially when you know exactly **how many times** you want the loop to run. The `range()` function generates a sequence of numbers.
23+
* `range(stop)`: Generates numbers starting from 0 up to (but *not* including) the `stop` number. The video shows `for x in range(10)` printing numbers from 0 to 9.
24+
* `range(start, stop)`: Generates numbers from `start` up to (but *not* including) the `stop` number. To print numbers from 1 to 10, you would use `range(1, 11)`.
25+
* `range(start, stop, step)`: Allows you to control the step size. You can count backwards with a negative step, like `range(9, -1, -1)` to get numbers from 9 down to 0.
26+
* The loop variable (like `i` or `x` in examples) takes on each value generated by `range()` in turn.
27+
* Using `for i in range(...)` is a way to code counter-based loops, useful when you need to repeat something a fixed number of times. For example, printing "Hello India" 10 times using `for i in range(10)`. Whatever is inside the loop body gets executed the specified number of times.
28+
29+
2. **Using `for` without `range()` (For-Each Style)**
30+
The sources highlight a "different variation of for loop" or "special feature of for loop which is called as for each". This is because a `for` loop is actually a **generic sequence iterator**. It can step through the items of *any* ordered sequence object, including strings, lists, and tuples. Files and dictionaries can also work.
31+
* Instead of generating numbers, this style of `for` loop directly assigns the **value of each item** in the sequence to the loop variable.
32+
* Example: `country = "India"` followed by `for letter in country: print(letter)`. This loop doesn't use `range()`.
33+
* Trace: The loop variable `letter` first becomes 'I', then 'n', then 'd', then 'i', and finally 'a'. For each `letter`, the code inside the loop (printing the letter) is executed.
34+
* This "for each" style is shown to be a more efficient and "easier to write" way to do something that would otherwise require manually accessing items by index using `range(len(...))`. It iterates over the string "one character at a time".
35+
36+
**Difference Between `while` and `for` Loops** 🤔
37+
38+
Both `while` and `for` are looping statements, and you'll see them in most code. They allow the computer to repeatedly do a piece of something again and again.
39+
40+
The key difference highlighted in the source "Tutorial on for loop and difference between while loop and for loop" is based on whether you **know the number of iterations in advance**.
41+
42+
* **`while` Loop:** This is a **general looping statement**. It keeps repeating as long as a specific condition is TRUE. You use `while` when you **do not know how many times the loop will execute**. The number of iterations cannot be predicted. You test the condition *before* executing the loop body.
43+
* Example given: Finding the number of digits in a number. You don't know how many digits a user will enter, so you loop until the number is processed. This is better done with a `while` loop because the range function cannot be defined in advance.
44+
* A `while True:` loop can run forever (an infinite loop) unless stopped by something like a `break` statement.
45+
46+
* **`for` Loop:** This is designed for **iterating across items in a sequence** (or more generally, an iterable). You should opt for a `for` loop when you **are certain** that the loop is going to execute for a specific, known number of times (an `n` number of times). The `range` function requires knowing the start and end points.
47+
* Example given: Finding the factorial of a number. The number of iterations (from 1 up to the number) is known. This makes the `for` loop, using `range()`, a suitable option.
48+
* A simple `for` loop (without `range`) is often preferred over a `while` with manual indexing when you just need to step across all the items in a sequence. It's generally simpler to code and often quicker than a `while`-based counter loop.
49+
50+
While a `while` loop can technically imitate a `for` loop using a counter, it requires more code (manual indexing and incrementing) and might run slower. The `for` loop is usually the first tool to reach for when you need to step through a sequence.
51+
52+
**Other loop-related concepts mentioned:**
53+
54+
* **Nested Loops:** You can put any type of loop (`while` or `for`) inside another loop, in any combination (`for` inside `for`, `while` inside `while`, `for` inside `while`, or `while` inside `for`). The sources show examples of nested `for` loops and `while` inside `for` loops.
55+
* **`break` and `continue`:** These are statements used specifically *inside* loops.
56+
* `break` exits the loop **immediately**.
57+
* `continue` jumps back to the **top** of the loop.
58+
* **Loop `else` Clause:** Both `while` and `for` loops can have an optional `else` block. This block is executed *only* if the loop finishes **normally** (meaning it did *not* exit because of a `break` statement).
59+
* **Practice:** To get better at coding and understanding loops, practice is essential. Going slowly, being patient, and using tools like pen and paper to diagram can help make things easier.
60+
61+
In essence, `for` is great for known repetitions or stepping through collections, while `while` is more flexible for loops that run based on a condition changing! 👍
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
---
2+
title: Nested for loop
3+
date: 2025-05-08
4+
tags:
5+
- Notes
6+
- IIT Madras
7+
excludeSearch: false
8+
weight: 40.1
9+
---
10+
11+
Right, let's talk about **nested `for` loops** with some emojis to make it super clear! 😊🔄
12+
13+
You know that a loop is something that makes your computer **repeat actions** multiple times. A `for` loop is one way to do this, especially useful for iterating over sequences or when you know you need to repeat something a specific number of times.
14+
15+
**Nested Loops:**
16+
Nesting simply means putting one loop **inside** another loop. Think of it like putting a box inside a box 📦📦.
17+
18+
The sources tell us you can nest loops in any combination:
19+
* `for` inside `for`
20+
* `while` inside `while`
21+
* `for` inside `while`
22+
* `while` inside `for`
23+
24+
**Nested `for` Loops in Detail:**
25+
When you have a `for` loop inside another `for` loop, it looks something like this:
26+
27+
```python
28+
for <outer_target> in <outer_object>: # Outer loop 🔄
29+
<outer_statements> # Code inside the outer loop
30+
for <inner_target> in <inner_object>: # Inner loop (nested inside the outer) ✨
31+
<inner_statements> # Code inside the inner loop ✨
32+
<more_outer_statements> # More code inside the outer loop (after the inner finishes for this iteration)
33+
# Code outside both loops
34+
```
35+
36+
Remember that **indentation** is key in Python to show which lines of code belong to which loop. The inner loop and its body are indented relative to the outer loop's body.
37+
38+
**How Execution Works:**
39+
This is the crucial part! 🚦
40+
1. The **outer** loop starts its first iteration. The `<outer_target>` variable gets the first item from the `<outer_object>`.
41+
2. The code inside the outer loop's body runs.
42+
3. When the computer reaches the **inner** loop, that loop starts running.
43+
4. The **inner** loop completes **all** of its iterations for the *current* value of the outer loop's target. The `<inner_target>` variable takes on each item from the `<inner_object>` in turn, and the `<inner_statements>` are executed for each of those items.
44+
5. Once the inner loop finishes (it has gone through all its items), the computer continues executing any remaining statements in the outer loop's body (those indented at the same level as the inner `for` header).
45+
6. Then, the outer loop moves to its **next** iteration. The `<outer_target>` variable gets the second item from the `<outer_object>`.
46+
7. The code inside the outer loop's body runs again.
47+
8. And once again, the **entire inner** loop runs from start to finish for this new value of the outer loop's target.
48+
9. This process repeats until the outer loop has finished all of *its* iterations.
49+
50+
**Example using `range()`:**
51+
A common use is with the `range()` function, often when you know exactly how many repetitions you need.
52+
Let's consider the "two brothers" analogy from the source. Suppose you have two brothers, S and T, who each pick one colour from a list of 7 colours (VIBGYOR) every day. To see all the combinations of colours they could pick, you could use nested loops:
53+
54+
```python
55+
s = "VIBGYOR" # The list of colours
56+
# We want to see all combinations of s[i] and s[j]
57+
for i in range(7): # Outer loop: Brother S picks a colour based on index i (0 to 6)
58+
# print(f"Brother S picked: {s[i]}") # Optional: see what outer loop is doing
59+
for j in range(7): # Inner loop: Brother T picks a colour based on index j (0 to 6)
60+
# For EACH pick of S (controlled by i), Brother T goes through ALL his 7 picks (controlled by j)
61+
print(f"Combination: {s[i]} {s[j]}") # Print the combination for S's pick and T's current pick
62+
```
63+
Trace example from source:
64+
* When `i` is 0 (V), `j` runs from 0 to 6. This prints "V V", "V I", "V B", ..., "V R".
65+
* After `j` finishes (goes from 0 to 6), the outer loop continues. `i` becomes 1 (I).
66+
* Then the inner loop starts again, and `j` runs from 0 to 6 again. This prints "I V", "I I", "I B", ..., "I R".
67+
* This repeats for each value of `i` until `i` is 6 (R), and `j` runs 0 to 6 one last time.
68+
69+
This demonstrates how the inner loop completes its entire run for every single step of the outer loop. The sources show this can be used for tasks like generating multiplication tables or finding prime numbers.
70+
71+
**Key Points about Nested `for` Loops:**
72+
* They are powerful for tasks involving **combinations** or processing multi-dimensional data like matrices (lists of lists).
73+
* You can use `break` and `continue` statements inside nested loops. A `break` statement inside the **inner** loop will *only* exit the inner loop; the outer loop will continue its next iteration.
74+
* The `else` clause can be used with either the inner or outer `for` loop (or both), and it executes if the loop finishes normally without a `break`.
75+
76+
Nested loops can seem a bit complex at first, but going slowly, being patient, and maybe even drawing it out on paper ✏️ helps make it easier. Practice makes perfect! 👍
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
---
2+
title: Tutorial on nested loops
3+
date: 2025-05-08
4+
tags:
5+
- Notes
6+
- IIT Madras
7+
excludeSearch: false
8+
weight: 40.2
9+
---
10+
11+
Okay, let's dive into **nested `for` loops**! 😊🔄
12+
13+
You already know that loops are super helpful for making the computer **repeat actions**. The `for` loop is great for this, especially when you're stepping through items in a sequence like a string or a list, or when you know you need to do something a specific number of times using `range()`.
14+
15+
**What are Nested Loops?** 🤔📦📦
16+
"Nested" just means putting one loop **inside** another loop. Think of it like having a main task (the outer loop) that requires doing another, smaller task (the inner loop) multiple times as part of the main task.
17+
18+
According to the sources, you can nest `while` and `for` loops in **any combination**:
19+
* `for` inside `for`
20+
* `while` inside `while`
21+
* `for` inside `while`
22+
* `while` inside `for`
23+
24+
Our focus here is on **`for` inside `for`**.
25+
26+
**How Nested `for` Loops Work** ⚙️🚦
27+
When you have a `for` loop inside another `for` loop, the execution flow is like this:
28+
29+
```python
30+
# Outer loop starts 🔄
31+
for <outer_variable> in <outer_sequence>:
32+
# Code inside the outer loop's body
33+
# This includes the entire inner loop 👇
34+
35+
# Inner loop starts ✨
36+
for <inner_variable> in <inner_sequence>:
37+
# Code inside the inner loop's body
38+
# This code runs for EACH iteration of the inner loop
39+
pass # Replace with actual code
40+
41+
# Code in the outer loop's body that runs AFTER the inner loop finishes
42+
pass # Replace with actual code
43+
44+
# Code outside both loops (runs after the outer loop finishes)
45+
```
46+
Remember that **indentation** is super important in Python to show what code belongs to which loop. The code inside the inner loop is indented further than the inner loop's `for` line, and the inner loop's `for` line (and any other code in the outer loop's body) is indented under the outer loop's `for` line.
47+
48+
The sources explain the execution like this:
49+
1. The **outer loop** starts. It takes the *first* item from the `<outer_sequence>` and assigns it to the `<outer_variable>`.
50+
2. The computer then goes into the outer loop's body and reaches the **inner loop**.
51+
3. The **inner loop** starts running, just like a regular `for` loop. It iterates through *all* the items in the `<inner_sequence>`. For *each* item in the `<inner_sequence>`, it assigns it to the `<inner_variable>` and runs the inner loop's body.
52+
4. Once the **inner loop has completed all its iterations** for the *current* item of the outer loop, the computer continues with any remaining code in the outer loop's body (the code indented at the same level as the inner `for` statement).
53+
5. Then, the **outer loop** goes back to its header to get the *next* item from the `<outer_sequence>`.
54+
6. Steps 2-5 repeat. For *every single item* in the outer sequence, the **entire inner loop runs from start to finish**.
55+
7. This continues until the outer loop has processed all its items.
56+
57+
**Example from Sources (VIBGYOR)** 🌈🔁
58+
One source gives a great example using a string `s = "VIBGYOR"` and nested `for` loops with `range(7)`. This is like seeing every possible combination of selecting two colours from the list (even picking the same colour twice).
59+
60+
```python
61+
s = "VIBGYOR"
62+
63+
for i in range(7): # Outer loop: i goes from 0 to 6 (representing the index of the first colour)
64+
# For each value of i...
65+
for j in range(7): # Inner loop: j goes from 0 to 6 (representing the index of the second colour)
66+
# ...the ENTIRE inner loop runs.
67+
# Inside the inner loop, we print the combination of the colour at index i and the colour at index j
68+
print(f"{s[i]} {s[j]}") # Printing combination based on indices
69+
```
70+
71+
Let's trace a bit, as shown in the source:
72+
* When `i` is `0` (the first iteration of the outer loop), `s[i]` is 'V'.
73+
* The inner loop starts. `j` goes from `0` to `6`.
74+
* `j` is `0`: prints "V V"
75+
* `j` is `1`: prints "V I"
76+
* `j` is `2`: prints "V B"
77+
* ...
78+
* `j` is `6`: prints "V R"
79+
* The inner loop finishes for `i=0`.
80+
* The outer loop moves to its next iteration. `i` becomes `1` (now `s[i]` is 'I').
81+
* The inner loop starts *again* from the beginning. `j` goes from `0` to `6`.
82+
* `j` is `0`: prints "I V"
83+
* `j` is `1`: prints "I I"
84+
* ...
85+
* `j` is `6`: prints "I R"
86+
* This pattern continues until `i` goes through all values up to 6, and for each `i`, `j` completes its full run from 0 to 6.
87+
88+
This is powerful for tasks like generating combinations, working with tables or matrices (lists of lists).
89+
90+
**Other Concepts with Nested Loops:**
91+
* **`break` and `continue`:** These can be used in nested loops. Crucially, a `break` statement inside the **inner loop** will **only** exit the inner loop. The outer loop will then continue its next iteration.
92+
* **`else` Clause:** Like single loops, nested loops can have an `else` clause. An `else` block on a loop executes *only* if the loop finishes normally (without hitting a `break`).
93+
94+
Nested loops might look a "little complex" at first, but the sources reassure us that it's "not at all complicated" and you'll master it with time. Taking it slow, being patient, maybe using a pen and paper to diagram what's happening with the variables can make things easier. As with learning anything new, especially coding, **practice makes one perfect**.
95+
96+
Keep practicing and happy coding! 👍💻

0 commit comments

Comments
 (0)