top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python for Loop

Introduction 

The for loop in Python is a fundamental control structure. First, it iterates through a sequence of items. Then, executes a code block for each item in the sequence. Python for loop can be used to iterate through elements such as integers in a range or items in a list. Essentially, to automate operations that need each item to be processed individually. 

Common applications include looping through lists, and strings, dictionaries, among others. It is mostly helpful for data analysis, manipulation, and transformation. for loops are a quick and effective technique to manage repeating tasks. Keep reading this tutorial to learn more about for loop in Python. 

Overview

In this tutorial, we will mainly deal with while loop in Python, python for loop, nested loop in Python, the different types of loop control statements, and much more.

while Loop in Python With Example

In Python, a while loop is a control structure that is used for repeatedly executing blocks of code as long as the given conditions are true. The syntax of a while loop looks like this:

while condition:

    # Code to be executed while the condition is true

    # This code block will keep running as long as the condition remains true

Here's a simple example of a while loop that counts from 1 to 5:

Code:

count = 1
while count <= 5:
    print(count)
    count += 1

In this example, the count variable starts at 1, and the loop will continue as long as count is less than or equal to 5. Inside the loop, the current value of count is printed, and then count is incremented by 1 in each iteration.

It's important to be cautious while using while loops to ensure that the loop eventually terminates. If the condition provided in the loop header never becomes false, you might end up with an infinite loop, causing your program to run indefinitely.

To prevent infinite loops, you can use mechanisms like user input or counter variables to control the loop's behavior. Here's an example of using a while loop for repeatedly asking users for input till the program is finally provided a valid number:

Code:

while True:
    try:
        num = int(input("Enter a number: "))
        print("You entered:", num)
        break  # Exit the loop if valid input is provided
    except ValueError:
        print("Invalid input. Please enter a valid number.")

In this example, the loop keeps running until the user provides a valid integer input. If the user enters something that can't be converted to an integer, a ValueError exception is caught, and an error message is displayed. Once the user enters a valid number, the break statement is used to exit the loop.

for Loop in Python With Example

In Python, a for loop is a control structure that iterates over a sequence (like a list, tuple, string, etc.) or other objects that are iterable. It repeatedly executes a block of code for each element in the sequence. The syntax of a for loop looks like this:

for element in sequence:

    # Code to be executed for each element in the sequence

Here's a simple example of a for loop that iterates over a list of numbers and prints each number:

Code:

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

In this example, the loop iterates over each element in the numbers list and prints it.

You can also use the range() function to generate a sequence of numbers and iterate over them in a for loop:

Code:

for i in range(1, 6):  # Generates numbers from 1 to 5 (inclusive)
    print(i)

In the above example, the range() function is used for generating the number sequence that starts from the first argument and ends before the second argument. In this case, it generates numbers from 1 to 5.

You can also iterate over strings:

Code:

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

This loop will iterate over each character in the string "Hello" and print each character.

Additionally, you can combine for loops with other control structures, such as using nested for loops to iterate over multiple sequences or using break and continue statements to control the loop's behavior.

Iterating by the Index of Sequences

Sometimes, you might need to iterate over a sequence using its index positions, rather than the values themselves. In Python, you can achieve this using the range() function and the length of the sequence. Here's how you can iterate by the index of sequences:

Code:

sequence = ["apple", "banana", "cherry", "date"]
for index in range(len(sequence)):
    item = sequence[index]
    print(f"Index {index}: {item}")

In this example, range(len(sequence)) generates a sequence of numbers from 0 to len(sequence) - 1, which are the valid index positions for the given sequence. The loop then iterates over these index positions, and within each iteration, you can access both the index and the corresponding value using sequence[index].

However, a more Pythonic way to achieve the same result is by using the enumerate() function, which provides both the index and the value in each iteration:

Code:

sequence = ["apple", "banana", "cherry", "date"]
for index, item in enumerate(sequence):
    print(f"Index {index}: {item}")

Using enumerate() is generally preferred because it's more concise and easier to read.

Remember that Python uses 0-based indexing, so the first element of a sequence is at index 0, the second element is at index 1, and so on.

Nested Loops in Python

Certainly! Nested loops in Python refer to the concept of having one loop inside another. This allows you to perform more complex iterations that involve multiple levels of iteration. You can nest any type of loop within another loop, such as for loops inside for loops, while loops inside for loops, and so on.

Here are a few examples of nested loops in Python:

Nested for Loops

Code:

for i in range(3):  # Outer loop
    for j in range(2):  # Inner loop
        print(f"Outer loop index: {i}, Inner loop index: {j}")

In this example, the outer loop is run three times, and the inner loop runs twice for each iteration of the outer loop. This results in a total of 3 * 2 = 6 iterations, and the program prints out the combination of indices from both loops.

Nested while Loops

Code:

i = 1
while i <= 3:  # Outer loop
    j = 1
    while j <= 2:  # Inner loop
        print(f"Outer loop index: {i}, Inner loop index: {j}")
        j += 1
    i += 1

This is equivalent to the previous example but using while loops instead.

Nested Loops With 2D Lists

Code:

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()  # Print a new line after each row

In this example, the outer loop is used for iterating over each of the rows in the 2D list matrix, and the inner loop iterates over the elements within each row, printing them out in a grid format.

Loop Control Statements

Loop control statements in Python help you alter the flow of loops based on certain conditions. The three loop control statements you mentioned are continue, break, and pass. Let's look at each one in detail:

Continue Statement

The continue statement is used within loops to skip the rest of the current iteration and proceed to the next iteration. This is particularly useful when you want to skip some part of the loop's body under specific conditions.

Code:

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

In this example, the loop iterates over the numbers 1 to 5. When i is equal to 3, the continue statement is executed, and the remaining part of the loop body for that iteration is skipped. As a result, the number 3 is not printed.

Break Statement

The break statement is used for exiting loop prematurely, regardless of whether the loop's condition is still met. It's often used when a specific condition is satisfied and you want to immediately stop the loop.

Code:

for i in range(1, 6):
    if i == 4:
        break
    print(i)

In this example, the loop iterates from 1 to 5. When i becomes 4, the break statement is executed, and the loop is terminated. As a result, only the numbers 1, 2, and 3 are printed.

Pass Statement

The pass statement is a placeholder statement that does nothing. It's used when statements are syntactically required but you don't want any action to be taken. It's often used as placeholders in code that you plan to fill in later.

Code:

for i in range(1, 4):
    if i == 2:
        pass
    else:
        print(i)

In this example, when i is 2, the pass statement is executed, essentially doing nothing. The loop continues to the next iteration. For other values of i, the corresponding value is printed.

The range() Function

The range() function is used for generating sequences of numbers that can be used for iterations, typically in for loops. It's often used to create a range of indices or values that you want to iterate over.

  • range(stop): Generates numbers from 0 up to (but not including) the stop value.

  • range(start, stop): Generates numbers from start up to (but not including) the stop value.

  • range(start, stop, step): Generates numbers from start up to (but not including) the stop value, incrementing by step at each iteration.

Here is an example of how to use the range() function:

Code:

# Loop from 0 to 4 (0, 1, 2, 3)
for i in range(4):
    print(i)
# Loop from 2 to 6 (2, 3, 4, 5)
for j in range(2, 6):
    print(j)
# Loop from 1 to 10 with step 2 (1, 3, 5, 7, 9)
for k in range(1, 10, 2):
    print(k)

Using Else Statement With for Loop

In Python, the else statement can be used with a for loop to specify a block of code that should run when the loop completes all its iterations without being interrupted by a break statement.

numbers = [1, 2, 3, 4, 5]
search_value = 3
for num in numbers:
    if num == search_value:
        print(f"Found {search_value} in the list.")
        break
else:
    print(f"{search_value} not found in the list.")

In this example, the for loop iterates through the numbers list to search for search_value. If the value is found, the break statement is executed, and the else block is skipped. However, if the loop completes without encountering a break, the else block is executed, indicating that the value was not found.

The combination of the else statement and a for loop can be helpful for scenarios where you want to execute specific code when a loop completes all its iterations without being prematurely interrupted by a break.

Conclusion

The for loop in Python is an essential and foundational feature in Python. Many industries worldwide strongly prefer experts with exceptional knowledge of programming languages such as Python. 

If you want to bag the best jobs in the most lucrative industries globally, look no further and take up a Computer Science course by upGrad. The courses by upGrad are designed by industry experts and tailored to meet the needs of the global job market. Visit upGrad today to know more. 

FAQs

1. How can I break out of a for loop prematurely?

You can exit the loop prematurely if a certain condition is met. To do this, use the “break” statement inside a for loop.  

2. Is it possible to skip the rest of the current iteration and continue with the next one?

It is possible to proceed to the next iteration by skipping the current iteration. To do this, you can use the “continue” statement. 

3. Can I nest for loops within each other?

Yes, you can nest one or more for loops within each other to create nested iterations, which can be helpful in working with multidimensional data structures.

4. Are there alternatives to for loops in Python?

Yes, Python offers other looping constructs like while loops and functional programming constructs like list comprehensions and the “map()” function that can sometimes provide more concise and efficient ways of achieving certain looping tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *