Python For Loops: Automate Code with Loops

PYTHON JOURNEY - Day 41 / 50 ...!! TOPIC – For Loops Today I entered the world of Loops! Specifically, the For Loop, which is used to iterate over a sequence (like a list, tuple, or string) and repeat a block of code. 1. Looping Through a List Instead of printing every item manually, a for loop does it in two lines. Python fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits: print(f"I love eating {fruit}!") 2. Using the range() Function The range() function is perfect when you want to run code a specific number of times. Python # This prints numbers 0 to 4 for i in range(5): print(f"Iteration number: {i}") 3. Looping Through a String Since strings are sequences of characters, you can loop through them too! Python name = "PYTHON" for letter in name: print(letter) Why Use For Loops? Automation: Perform the same action on thousands of items instantly. DRY Principle: "Don't Repeat Yourself" — loops keep your code short and clean. Data Processing: Essential for analyzing lists of numbers or text data. Mini Task Write a program that: Creates a list of numbers: [1, 2, 3, 4, 5]. Uses a for loop to calculate the square of each number (number * number). Prints: "The square of <number> is <result>." #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity

  • diagram

To view or add a comment, sign in

Explore content categories