Python For Loops

Loops are a fundamental concept in programming, allowing us to perform repetitive tasks efficiently. In Python, one of the most widely used loop structures is the ‘For’ loop.

A For loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

For Example

languages = [‘Swift’, ‘Python’, ‘Go’, ‘JavaScript’]

 # run a loop for each item of the list

for language in languages:

print(language)

 Understanding ‘For’ loop

A for loop is used in Python to iterate over a sequence, such as a list, tuple, string, or range, and execute a block of code for each item in the sequence. The basic structure of a for loop in Python is as follows:

for item in sequence:

# Code to be executed for each item in the sequence

Here’s a breakdown of the components:

  • for: This keyword marks the beginning of the for loop.
  • item: This variable is used to represent each item in the sequence as the loop iterates over it.
  • sequence: Replace this with the iterable object you want to loop through. This can be a list, tuple, string, range, or any other iterable.

The for loop is a versatile and powerful tool that can help you automate tasks and process data efficiently.

Basic syntax of a For loop

The basic syntax of the for loop in Python looks something similar to the one mentioned below.

for itarator_variable in sequence_name:

         Statements

        . . .

         Statements

Let me explain the syntax of the Python for loop better.

  •     The first word of the statement starts with the keyword “for” which signifies the beginning of the for loop.
  •     Then we have the iterator variable which iterates over the sequence and can be used within the loop to perform various functions
  •     The next is the “in” keyword in Python which tells the iterator variable to loop for elements within the sequence
  •     And finally, we have the sequence variable which can either be a list, a tuple, or any other kind of iterator.
  •     The statements part of the loop is where you can play around with the iterator variable and perform various functions.

Examples of ‘For’ loop

  1. Looping through a list

fruits = [“apple”, “banana”, “cherry”]

 for fruit in fruits:

print(fruit)

In this example, we use a for loop to iterate through a list of fruits and print each fruit’s name. The loop iterates over the fruits list, and the fruit variable represents each item in the list.

  1. Looping through a string

sentence = “Hello, World!”

 for char in sentence:

if char != ” ” and char != “,” and char != “!”:

     print(char)

In this case, we loop through a string and print each character except for spaces, commas, and exclamation marks. The char variable represents each character in the sentence string.

  1. Using the range function

for number in range(1, 6):

print(number)

Here, we use the range function to generate a sequence of numbers from 1 to 5 (inclusive). The for loop iterates through this range, and the number variable represents each number in the sequence.

 Nested For Loops

Python allows you to nest for loops, which means you can include one for loop inside another. This is useful for performing more complex iterations, such as iterating through a list of lists.

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

]

 for row in matrix:

for element in row:

     print(element)

In this example, we use nested for loops to iterate through a 2D matrix. The outer loop iterates through each row, and the inner loop iterates through the elements in each row.

 Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

Continue Statement

The continue statement in Python returns the control to the beginning of the loop.

# Prints all letters except ‘e’ and ‘s’

for letter in ‘geeksforgeeks’:

         if letter == ‘e’ or letter == ‘s’:

                     continue

         print(‘Current Letter :’, letter)

Output:

Current Letter : g

Current Letter : k

Current Letter : f

Current Letter : o

Current Letter : r

Current Letter : g

Current Letter : k

Break Statement

The break statement in Python brings control out of the loop.

for letter in ‘geeksforgeeks’:

 # break the loop as soon it sees ‘e’

# or ‘s’

if letter == ‘e’ or letter == ‘s’:

break

 print(‘Current Letter :’, letter)

Output:

Current Letter : e

Pass Statement

We use pass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.

# An empty loop

for letter in ‘geeksforgeeks’:

         pass

print(‘Last Letter :’, letter)

Output:

Last Letter : s

 Using else Statement with for Loop

A loop expression and an else expression can be connected in Python.

After the circuit has finished iterating over the list, the else clause is combined with a for Loop.

The following example demonstrates how to extract students’ marks from the record by combining a for expression with an otherwise statement.

# code to print marks of a student from the record 

student_name_1 = ‘Itika’ 

student_name_2 = ‘Parker’ 

 # Creating a dictionary of records of the students 

records = {‘Itika’: 90, ‘Arshia’: 92, ‘Peter’: 46} 

def marks( student_name ): 

for a_student in record: # for loop will iterate over the keys of the dictionary 

if a_student == student_name: 

return records[ a_student ] 

break 

else: 

return f’There is no student of name {student_name} in the records’  

     # giving the function marks() name of two students 

print( f”Marks of {student_name_1} are: “, marks( student_name_1 ) ) 

print( f”Marks of {student_name_2} are: “, marks( student_name_2 ) )

Output:

Marks of Itika are:  90

Marks of Parker are:  There is no student of name Parker in the records

 Conclusion

for loops are a powerful feature in Python for automating repetitive tasks and processing data from various data structures. Understanding how to use them effectively is crucial for writing efficient and organized code. Practice with examples like the ones provided in this blog post to improve your Python programming skills. Once you’re comfortable with for loops, you’ll be better equipped to handle a wide range of programming challenges and tasks.

Visited 1 times, 1 visit(s) today