Iterative Programming in Python
Iterative Programming in Python
uses loops to repeat a block of code until a certain condition is met. This
allows you to perform tasks such as printing a list of items, summing the
values in a list, or searching for a specific item in a list.
while loop
The while loop is an indefinite loop, meaning that it will execute the block of
code inside the loop until the condition is met.
For example, the following code will print the numbers from 1 to 10:
Python
i = 1
for loop
The for loop is a definite loop, meaning that it will execute the block of code
inside the loop a specific number of times.
For example, the following code will print the same numbers as the previous
example, but using a for loop:
Python
for i in range(1, 11):
print(i)
Nested loops
You can also nest loops to create more complex iterative logic. For example,
the following code will print a multiplication table:
Python
for i in range(1, 11):
for j in range(1, 11):
print(i * j)
Abnormal termination of loops
You can use the break and continue statements to terminate loops
abnormally. The break statement will immediately terminate the loop, while
the continue statement will skip the rest of the current iteration and move on
to the next iteration.
For example, the following code will print the numbers from 1 to 10, but it will
stop printing numbers when it reaches the number 5:
Python
i = 1
The while/else and for/else statements allow you to execute a block of code
after the loop has finished executing. For example, the following code will print
a message if the while loop terminates because the condition is no longer
met:
Python
i = 1
Conclusion