This lesson will explain to you what Iterative statements are and how to iterate over a list of elements using various for-loop and while-loop versions with examples.
Python’s for Loop is used to loop through iterable objects repeatedly. Any sequence or iterable variable can be iterated using a for-loop like a string, list, dictionary, set, or tuple.
The process of traversing a sequence entails Iteration.
Basic Syntax
for element in sequence: body loop
Example
numbersList = [1, 3, 4, 5, 40, 10] squareVar = 5 # iterate over the list for i in numbersList: squareVar = i * i print("The Square of ",i," = ", squareVar)
Output
The Square of 1 = 1 The Square of 3 = 9 The Square of 4 = 16 The Square of 5 = 25 The Square of 40 = 1600 The Square of 10 = 100
We can use the loops’ range() method to iterate through a list of numbers. You can use indexing to iterate through a sequence by combining it with the len() or range() function. Here’s an illustration.
for i in range(1, 6): print(I)
With the help of the range() method, we may produce a series of numbers. range(6) will produce values between 0 and 5. (6 numbers).
In the range function, Start, stop, and step size can also be defined as the range(start, stop, step size). If the step size is not given, it defaults to 1 like print(list(range(4, 11, 1))).
Since doing so would be inefficient, this function does not save all the values in memory. As a result, it retains the start, stop, and step size and continuously generates the next number.
We can utilize the function list to have this function output every item () like print(range(6)), print(list(range(6))) and print(list(range(2, 5))).
The below range function example will make this clear.
Example
for i in range(1, 6): print(i) print(range(6)) print(list(range(6))) print(list(range(2, 5))) print(list(range(4, 11, 1)))
Output
1 2 3 4 5 range(0, 6) [0, 1, 2, 3, 4, 5] [2, 3, 4] [4, 5, 6, 7, 8, 9, 10]
While a specific condition is true, Python’s while loop statement continually runs a code block. In a ‘while loop’, the condition is tested at the beginning of each Iteration, and if it is true, the body of the ‘while loop’ is then run. The controller exits the block when the condition turns False. We can use the loops’ range() method to iterate through a list of numbers. You can use indexing to iterate through a sequence by combining it with the len() function. Here’s an illustration.
Basic Syntax
while condition : while loop body
Example
Number = 1 sum =0 # condition: Run loop till Number is less than 3 while Number < 10: print('Number-',Number) Number = Number + 1 sum =sum+Number print('Sum -',sum)
Output
Number- 1 Number- 2 Number- 3 Number- 4 Number- 5 Number- 6 Number- 7 Number- 8 Number- 9 Sum - 54
The condition in the program will be True if our counter variable I is less than or equal to the number. (10 in our program). The counter variable’s value needs to be raised in the Loop’s main body, which is crucial (and mostly forgotten). Failure will lead to an endless loop (never-ending Loop).
When the number of iterations is unidentified, we employ a while loop. We don’t know how many tries a user could need to estimate the right number, for instance, if you want them to guess your lucky number between 1 and 10. Use a while loop in these circumstances.
It means iterations that last an indefinite amount of time. Request a lucky number guess from the user. You have no idea how many tries the user will take to get it right. It can be 1, 20, or indefinitely. Use a while loop in these circumstances.
Finite for Loop Iteration refers to unchanging the number of iterations. Print out the two times table. You already know how many iterations you need in this situation; here, 10 iterations are required. In this situation, utilize Loop.
Now, the question of when and why to utilize a while loop can come up.
Automate and repeat tasks: As we are all aware, the while loop efficiently automates and repeats tasks by repeatedly executing code blocks until the condition is met. Instead of using the ‘for-loop’ when the user is unsure of the number of iterations before execution, use a ‘while loop’. The while loop will execute as often as required to finish a specific task.
Reduce complexity: writing a while loop is simple. We can avoid writing the sentences again by using the loop. Instead, we may write the statements we want to run repeatedly inside the loop’s body, simplifying the code. The loop will run indefinitely if the while loop’s code doesn’t alter the variables being checked in the loop condition.