For Loops

tags: #python/documentation/python_loops

Definite Loops Using For

The for loop executes a block of code in succession or iteration for each element in an iterable object or a range of numbers. We can create a for loop using the for keyword:

for loop_var in iterable_obj: #loop_var = iterable_var
	# body of the loop to execute some task
	<statement>
	...

Looping through a range of values:

for i in range(val):
	<statement>
	...
What makes this different from a While Loops?

In a while loop, a count variable is explicitly initialized before the loop, and the loop continues to execute as long as a specified condition is true. The count variable is typically updated within the loop body. As a result, the loop may or may not have a fixed number of iterations.

While loops require explicit control over the iteration.

Flow of Execution

Iteration Variables

The iteration variable takes on the value of each element in the iterable object during each iteration of the loop.

Summary of Flow

  1. The iterable variable iterates through an iterable object.
  2. The body of the code is executed once for each successive item in the iterable object.
  3. The iteration variable moves through each item in the object and terminates the loop after iterating through the entire object.

Pasted image 20240110003459.png

Terminating Condition

The terminating condition of the for loop occurs when the program has iterated through each item in an iterable object.

Powered by Forestry.md