🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Python for Loop

Python For Loop

In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. The basic syntax of a for loop is as follows:

for variable in sequence:
    # Code to be executed for each iteration

Here's a more detailed breakdown:

  1. The for keyword is used to start the loop.
  2. variable is a variable that takes the value of the next element in the sequence for each iteration of the loop.
  3. sequence is the iterable object over which the loop iterates.
  4. The indented code block following the for statement is the body of the loop, and it is executed for each element in the sequence.

Example with a List:

fruits = ['apple', 'banana', 'orange']

for fruit in fruits:
    print(fruit)

In this example, the for loop iterates over the list of fruits, and the print(fruit) statement is executed for each fruit in the list.

Example with Range:

for i in range(5):
    print(i)

In this example, the for loop iterates over the range of numbers from 0 to 4, and the print(i) statement is executed for each value of i in the range.

Example with Strings:

word = "Python"

for char in word:
    print(char)

In this example, the for loop iterates over each character in the string "Python", and the print(char) statement is executed for each character.

Using enumerate for Index and Value:

fruits = ['apple', 'banana', 'orange']

for index, value in enumerate(fruits):
    print(f"Index: {index}, Value: {value}")

The enumerate function is used to iterate over both the index and value of the elements in the list.

Using break and continue:

fruits = ['apple', 'banana', 'orange']

for fruit in fruits:
    if fruit == 'banana':
        continue  # Skip 'banana' and move to the next iteration
    print(fruit)
    
    if fruit == 'orange':
        break  # Stop the loop when 'orange' is encountered

The continue statement skips the rest of the code in the loop for the current iteration, while the break statement terminates the loop prematurely.

The for loop is a powerful construct for iterating over sequences and performing repetitive tasks in a concise manner.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.