TGViewer
Data Science & Machine Learning Data Science & Machine Learning @datasciencefun · 77.8K subscribers
Post #4060 4.2K
✅ Python Loops (for & while)

Loops help repeat tasks automatically — very important for data processing and automation.

🔹 1. What are Loops?
Loops repeat a block of code multiple times.
👉 Used in:
✅ Data cleaning
✅ Data analysis
✅ Machine learning
✅ Automation

🔥 2. for Loop (Most Used) ⭐
Used to iterate over a sequence (list, string, range).

✅ Basic Syntax
for variable in sequence:
    # code

✅ Example — Print Numbers
for i in range(5):
    print(i)

Output: 0 1 2 3 4
👉 range(5) → generates numbers from 0 to 4.

✅ Loop Through List (Very Important)
numbers = [10, 20, 30]
for num in numbers:
    print(num)

👉 Used heavily in data science.

🔥 3. while Loop
Runs until condition becomes False.

✅ Syntax
while condition:
    # code

✅ Example
x = 1
while x <= 5:
    print(x)
    x += 1

Output: 1 2 3 4 5
👉 Important: Update condition to avoid infinite loop.

🔹 4. Loop Control Statements (Very Important)

✅ break → stop loop
for i in range(5):
    if i == 3:
        break
    print(i)

Output: 0 1 2

✅ continue → skip current iteration
for i in range(5):
    if i == 3:
        continue
    print(i)

Output: 0 1 2 4

🎯 Today’s Goal
✅ Use for loop
✅ Use while loop
✅ Understand break & continue

Double Tap ♥️ For More
  • ❤ 16
  • 👍 1
More from @datasciencefun
  1. Oct 15, 2026Post #4665
  2. Oct 15, 2026Post #4664
  3. Oct 15, 2026Post #4663
  4. Oct 15, 2026Post #4662
  5. Oct 13, 2026𝗧𝗢𝗣 𝗙𝗥𝗘𝗘 𝗖𝗢𝗨𝗥𝗦𝗘𝗦 𝗧𝗢 𝗕𝗢𝗢𝗦𝗧 𝗬𝗢𝗨𝗥 𝗦𝗞𝗜𝗟𝗟𝗦 𝗜𝗡 𝟮𝟬𝟮𝟲! Explor…
  6. Oct 12, 2026Used when you want to perform calculations for each department. Simple rule: DISTINCT → Gi…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →