Ticker

6/recent/ticker-posts

For Loop in Python

For Loop in Python

Overview:
The for loop is a fundamental control structure in Python used for iterating over a sequence (such as a list, tuple, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence, making it easier to handle repetitive tasks efficiently.

Syntax:

python
for item in sequence:
# Code block to be executed for each item

Explanation:

  • item: This variable represents the current item being processed in each iteration of the loop. You can choose any variable name that is valid in Python.
  • sequence: The sequence or iterable object over which the loop will iterate.

Example:

Let's say we have a list of numbers and want to print each number using a for loop:

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

for num in numbers:
print(num)

In this example, the for loop iterates through each element in the numbers list and prints the value of num.

Output:


1
2
3
4
5

Using range() with for loop:

The range() function generates a sequence of numbers, and it is commonly used with for loops to iterate over a specific range.

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

Output:


1
2
3
4
5

Nested for loop:

You can also nest one for loop inside another to handle more complex iterations, like iterating over a 2D list.

python
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

for row in matrix:
for element in row:
print(element)

Output:


1
2
3
4
5
6
7
8
9

Remember to indent the code blocks correctly to avoid syntax errors and make sure to properly define the sequence or iterable to be looped over. The for loop is a powerful tool for automating repetitive tasks and processing data in Python.

Post a Comment

0 Comments