Friday, 13 January 2023

Python for loop

 

A for loop in Python allows you to iterate over a sequence of elements such as a list, tuple, string, or dictionary. The basic syntax of a for loop is as follows:

for variable in sequence:
    # code to be executed

The variable is used to store the current value of the element being iterated over, and the sequence is the collection of elements that you want to iterate over. Here's an example of how to use a for loop to iterate over a list of numbers:

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

This will output:

1
2
3
4
5

You can also use the range() function to create a sequence of numbers to iterate over. The range() function can take one, two, or three arguments:

  • range(stop) generates a sequence of integers from 0 to stop-1
  • range(start, stop) generates a sequence of integers from start to stop-1
  • range(start, stop, step) generates a sequence of integers from start to stop-1 with a step of step

Here's an example of using the range() function with a for loop:

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

This will output the same as the previous example.

You can also iterate over the items of a dictionary using a for loop, for example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
 
for key in my_dict:
    print(key, my_dict[key])

This will output:

name John
age 25
city New York

You can also use the items() method to access the key-value pairs of a dictionary and iterate over them:

for key, value in my_dict.items():
    print(key, value)

The for loop also allows you to use the enumerate() function to access the index and value of an element in a sequence. Here's an example of how to use the enumerate() function with a for loop:

fruits = ['apple', 'banana', 'orange']
 
for index, fruit in enumerate(fruits):
    print(index, fruit)

This will output:

0 apple
1 banana
2 orange

You can also use break and continue statements inside a for loop to control the flow of execution. The break statement is used to exit the loop completely, while the continue statement is used to skip the current iteration and move on to the next one.

for num in range(1,6):
    if num == 3:
        break
    print(num)

This will output:

1
2
for num in range(1,6):
    if num == 3:
        continue
    print(num)

This will output:

1
2
4
5

Python for loops are a very powerful feature that allows you to easily iterate over a variety of data types. 




Amelioration

This article was researched and written with the help of ChatGPT, a language model developed by OpenAI.

 Special thanks to ChatGPT for providing valuable information and examples used in this article.

 

No comments:

Post a Comment