1.4 Loops (for, while)

Loading content...

1.4 Loops (for, while)

Module 4 — Python Loops 🔁 | Python for Machine Learning 🐍 Module 4 • Python for Machine Learning Master for and while loops — the engines that power every ML algorithm, from training neural networks to processing millions of data rows 🚀 Imagine you're a DJ with a playlist of 50 songs 🎶. You don't manually click "play" 50 times — you press Play All, and the music app automatically plays each song one after another. That's exactly what a loop does in programming! It takes a set of instructions and repeats them — once for each item, or while a condition stays true 🔁. 📖 Loop: A programming structure that repeats a block of code multiple times — either for each item in a sequence, or while a condition remains True. Without loops, you'd write the same code over and over. Imagine printing 1000 student names — would you write 1000 print() statements? 😱 Of course not! A loop does it in 3 lines. 📧 Real-World Loop Examples 📧 Send an email to each person in a contact list 🔢 Calculate the sum of all student scores 🔍 Search for a name in a database 📊 Process each row in a dataset 🎮 Game loop: keep playing while player is alive 🏦 Check each transaction for fraud 🤖 Train an ML model for 100 epochs 📸 Apply a filter to every pixel in an image 💡 ML Connection: Every machine learning model uses loops! Training a neural network means looping through data thousands of times. Understanding loops is essential for ML. ✅ True or False — Activity 1 A loop lets you repeat a block of code multiple times without writing it again and again. Before we dive in, let's learn the words you'll see throughout this module 📚. Repeats code for each item in a sequence Repeats code while a condition is True Generates a sequence of numbers One single pass through the loop body Loop runs 5 times = 5 iterations The variable that changes each loop cycle Exits the loop immediately Skips the current iteration, goes to next A loop inside another loop Gives you index AND value together Pairs items from two lists together 🧠 Quick Check — Activity 2 Which keyword is used to exit a loop immediately, even if it hasn't finished all iterations? A teacher takes attendance by going through the class list one by one 📋: "Alice?" ✋ "Bob?" ✋ "Charlie?" ✋ — for each name in the list, the teacher calls it out. A for loop works the same way — it goes through each item one by one and runs your code on it. The variable takes the value of each item in the sequence, one at a time. # Print each fruit in the list fruits = ["apple", "banana", "cherry"] print(f"I love {fruit}! 🍎") Often you want to loop a specific number of times (like "do this 10 times"). The range() function generates a sequence of numbers for you 🔢. Loop 5 times (starts at 0) Numbers 1 to 5 (end is excluded) ⚠️ Common trap: range(5) gives you 0 through 4, not 1 through 5! The end value is always excluded. # Even numbers from 0 to 8 🔥 Pattern: range(start, stop, step) — start is included, stop is excluded, step is how much to jump. 🧠 Quick Check — Activity 3 What numbers does range(2, 7) produce? ✍️ Fill in the Blank — Activity 4 Complete the code to loop exactly 10 times (i = 0, 1, 2, ..., 9): 🎬 Loop Animation — Watch It Work! See how a for loop processes items one by one, like a runner going around a track 🏃‍♂️. Watch the runner (🔵) process each fruit from the list, one lap at a time. Press ▶ Play to see the for loop in action! 🎬 If you write for i in range(3, 9):, how many times will the loop body execute? 📚 Iterating Collections & The while Loop 📦 Looping Through Different Collections Python's for loop can iterate through any sequence — lists, strings, and even dictionaries! 🎉 📦 Iterating different types colors = ["red", "green", "blue"] # 🔤 Loop through a STRING (character by character) # 📖 Loop through a DICTIONARY student = {"name": "Alice", "age": 21, "grade": "A"} for key, value in student.items(): 🚪 Analogy: The Nightclub Bouncer A bouncer at a club keeps letting people in while the club isn't full 🚪. The moment the club reaches capacity, the bouncer stops. A while loop checks its condition before each iteration. If the condition is True, it runs the code. If False, it stops ✋. Runs as long as condition is True. You must change the condition inside the loop, or it will run forever! ♾️ print(f"Countdown: {count}") count -= 1 # MUST update! ⚖️ for vs while — When to Use Which? ✅ You know how many times to loop ✅ You're iterating through a list, string, or range ✅ Processing each item in a collection ✅ Example: "Print each student name" ✅ You don't know how many iterations ✅ Loop depends on a changing condition ✅ Waiting for user input or an event ✅ Example: "Keep asking until correct password" 🧠 Quick Check — Activity 6 What is the output of this code? 🤔

Subject: Python for Machine Learning | Chapter: Chapter 1: Python Essentials

1.3 Conditional Statements (if elif else) Chapter 1: Python Essentials 1.5 Functions and Return Values
Topics
Chapter 1: Python Essentials
Chapter 2: Python for Data Science
© Copyright © 2020 ALGOPK . All Rights Reserved.