Python For Loop - Part 3 PDF
Document Details
Uploaded by TantalizingConnemara41
Tags
Summary
This document provides a tutorial on for loops in Python. The tutorial explains how to use for loops in different code scenarios. The key concepts and applications of for loops in Python are highlighted.
Full Transcript
For Loop in Python Part 3 02 codebasics.io Po, today we will learn about loops in Python. Loops? That sounds like running, M...
For Loop in Python Part 3 02 codebasics.io Po, today we will learn about loops in Python. Loops? That sounds like running, Master Shifu. Ha-ha, Po, it’s not that kind of loop. It’s a programming concept where we can run a block of code several times. Source: Kung Fu Panda 03 codebasics.io So we can write shorter, more concise code that's easier to understand and maintain? Yes, Po. We can use loops to perform repetitive tasks, like printing numbers. This sounds like a fun mission, Master! Let’s get started! Source: Kung Fu Panda 04 codebasics.io In Python, loops are a fundamental concept for performing repetitive tasks efficiently. Loops allow you to execute a block of code multiple times, which is especially useful for operations involving lists, files, or repeated calculations. Python provides two primary types of loops: for loops and while loops. 05 codebasics.io For Loop: The for loop is commonly used to iterate over a sequence, such as a list, tuple, dictionary, set, or string. It executes a block of code for each item in the sequence, making it ideal for fixed, known iterations. Syntax: For Loop Flow Chart: 06 codebasics.io Example: Explanation: Dish = ["Pizza","Burger","French fries"] Price = [100,90,30] total_price=0 Note: [ ] Used to access elements of the list. index() method is used to return the position at the first occurrence of the specified value. Dish -> Burger Dish.index("Burger") -> 1 07 codebasics.io Loop for the element " Pizza " is completed Initially total_price= 0 Now total_price = 100 We did not reach the end of the list " Dish", so now we perform a loop for the next element "Burger" 08 codebasics.io Loop for the element " Burger " is completed Change in total_price value: 100 -> 190 We did not reach the end of the list " Dish", so now we perform a loop for the next element "French Fries" 09 codebasics.io Loop for the element " French Fries " is completed Change in total_price value: 190 -> 220 We reached the end of the list " Dish", so now we will exit the loop 10 codebasics.io Print(total_price) Output: 220 11 codebasics.io Wow! The for-loop concept is crystal clear now—ready to loop through every item in a list; can we dive into the while loop after a quick break? Ha Ha! Sure, Po! I’ll cover the while loop in our next resource. Source: Kung Fu Panda Scan the QR code for more content join the WhatsApp Channel today! E N A B L I N G C A R E E R S Like this way of learning? Check our Python learning at codebasics.io codebasics.io