All You need to know about Python For Loop

A for loop is a type of loop in Python that allows you to execute a block of code repeatedly for a specific number of times. Here’s the general syntax for a for loop:

for variable in sequence:
    # code block to execute

Here’s an example of how you could use a for loop to iterate over a list of numbers and print each one:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

In this example, we define a list of numbers and then use a for loop to iterate over each number in the list. The num variable takes on the value of each element in the list, one at a time, and the print statement outputs each number to the console.

You can also use a for loop to iterate over a range of numbers using the range function. Here’s an example:

for i in range(1, 6):
    print(i)

In this example, we use the range function to create a sequence of numbers from 1 to 5, and then we use a for loop to iterate over each number in the sequence and print it to the console.

You can also use a for loop to iterate over a string, which will iterate over each character in the string. Here’s an example:

message = "Hello, World!"

for char in message:
    print(char)

In this example, we use a for loop to iterate over each character in the string message and print it to the console.

These are just a few examples of how you can use a for loop in Python. For loops are a powerful tool for iterating over sequences of data, and they can be used in a wide variety of applications. I hope this helps! Let me know if you have any other questions.

Leave a Reply