Tuple

Tutorial for Python For Loop

Python’s for loop is an iteration structure that allows you to loop through a sequence, such as a list, tuple, or string. Below is a step-by-step tutorial to help you understand how to use for loops in Python.

Step 1: Basic Syntax

The basic syntax for a for loop in Python is:

Python
for variable in sequence:
    # code to be executed

Here, variable is a temporary variable that takes the value of each element in sequence one by one. The indented code under the for statement is executed for each value of variable.

Step 2: Simple Example with a List

Here’s an example that prints each item in a list:

Python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

This would output:

1
2
3
4
5

Step 3: Looping Through Strings

You can also loop through each character in a string:

Python
text = "Hello"
for char in text:
    print(char)

Output:

H
e
l
l
o

Step 4: Looping Through Tuples

Looping through a tuple is similar to looping through a list:

Python
tuple_data = (1, 2, 3)
for item in tuple_data:
    print(item)

Output:

1
2
3

Step 5: Looping Through Dictionaries

For dictionaries, you can loop through keys, values, or both.

Python
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Loop through keys
for key in my_dict:
    print(key)

# Loop through values
for value in my_dict.values():
    print(value)

# Loop through both keys and values
for key, value in my_dict.items():
    print(key, value)

Step 6: Using range() Function

The range() function allows you to generate a sequence of numbers to loop through.

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

Output:

0
1
2
3
4

Step 7: Nested Loops

You can also have loops within loops, known as nested loops:

Python
for i in range(3):
    for j in range(2):
        print(i, j)

Output:

0 0
0 1
1 0
1 1
2 0
2 1

Step 8: Break and Continue

  • break: Stops the loop immediately.
  • continue: Skips the current iteration and continues with the next.
Python
for num in [1, 2, 3, 4, 5]:
    if num == 3:
        break
    print(num)

Output:

1
2

Step 9: Using else With for Loop

An else block can be added to a for loop and is executed when the loop finishes iterating.

Python
for i in range(3):
    print(i)
else:
    print("Loop done!")

Output:

0
1
2
Loop done!

I hope this step-by-step tutorial helps you understand for loops in Python! Feel free to experiment and try different variations to get a deeper understanding.