0% found this document useful (0 votes)
13 views

Iterative Programming in Python

Uploaded by

kengeeky2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Iterative Programming in Python

Uploaded by

kengeeky2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Iterative Programming Iterative programming is a programming paradigm that

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

while i <= 10:


print(i)
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

while i <= 10:


print(i)
if i == 5:
break
i += 1

while/else and for/else

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

while i <= 10:


print(i)
i += 1
else:
print("The loop has finished executing.")

Conclusion

Iterative programming is a powerful tool for performing repetitive tasks. By


understanding loops, you can write more efficient and concise code.

You might also like