Python For Loop Examples: A Comprehensive Guide for Beginners

Loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly. Python provides several loop mechanisms, with the for loop being one of the most versatile. The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. Here’s an in-depth look at the for loop with various examples:

Basic for Loop with Lists

Example:

This loop iterates through each item in the list fruits and prints each item.

for Loop with Strings

Example:

This example demonstrates iterating over each character in the string “banana” and printing each character.

for Loop with range()

The range() function returns a sequence of numbers and is often used to execute a loop a certain number of times.

Example:

This loop will print numbers 0 to 4, as range(5) generates numbers from 0 up to (but not including) 5.

Nested for Loops

You can nest for loops inside each other to iterate over more complex data structures.

Example:

This example prints each combination of color and fruit.

for Loop with enumerate()

The enumerate() function adds a counter to an iterable and returns it as an enumerate object. This can be useful for getting the index of each item in the loop.

Example:

This loop prints the index of each item in the list fruits alongside the item itself.

for Loop with Dictionaries

To iterate through both keys and values in a dictionary, you can use the .items() method.

Example:

This loop prints each key-value pair in the person dictionary.

for Loop with List Comprehension

List comprehension offers a concise way to create lists. It consists of brackets containing an expression followed by a for clause.

Example:

This creates a list of square numbers (from 0 to 9) and prints the list.

Break and Continue

You can control the flow of your for loops with break and continue.

Using break:

This loop will stop when “banana” is encountered.

Using continue:

This loop will skip “banana” and continue with the next item.

Understanding and effectively using for loops in Python enhances your ability to work with sequences and perform repetitive tasks efficiently. Through these examples, you can see how versatile the for loop is for iterating over various data structures.

Leave a Reply

Your email address will not be published. Required fields are marked *