Iteration and Looping in Python Control Structures

In this Python article we want to learn about Iteration and Looping in Python Control Structures, so Python provides different control structures to help programmers automate repetitive tasks. two important Python control structures are iteration and looping. iteration allows you to execute a block of code repeatedly, while looping allows you to iterate over a collection of data.

 

Iteration

Iteration is the process of repeatedly executing a block of code. Python provides two types of iteration, for loops and while loops.

 

For Loops

For loop is used to iterate over a sequence of data, such as a list or a tuple. this is is an example of for loop that prints each item in a list.

 

 

This will be the result

Iteration and Looping in Python Control Structures
Iteration and Looping in Python 

 

 

You can also use the range function to generate a sequence of numbers to iterate over. 

 

 

While Loops

Python while loop is used to iterate until a certain condition is met. this is is an example of a while loop that counts down from 10 to 1, in this example while loop continues to iterate as long as the value of i is greater than 0. after that print statement prints the value of i, and the i -= 1 statement decrements the value of i by 1.

 

 

Looping

Looping is the process of iterating over a collection of data. Python provides several ways to loop over data, including for loops, while loops and list comprehensions.

 

As we saw earlier, a for loop can be used to iterate over a sequence of data. this is an example of a for loop that sums the values in a list.

In this example for loop iterates over the numbers list and adds each value to the total variable.

 

 

This will be the result

Python For Loop Example
Python For Loop Example

 

Now let’s talk about while loop, while loop can also be used to loop over data. this is an example of a while loop that removes all occurrences of a value from a list:

 

List comprehension is an easy way to create a new list by looping over an existing list. this is an example of a list comprehension that squares each number in a list.

 

 

 

This will be the result

Iteration and Looping in Python Control Structures
Iteration and Looping in Python Control Structures

 

 

Learn More

Leave a Comment