2. Looping (or) Iterative (or) Repetitive Statements
The purpose of looping statements is to perform a specific operation repeatedly for a finite number of times until the test condition becomes false.
In Python programming, there are two types of looping statements:
- for loop (or for...else loop)
- while loop (or while... else loop)
When working with while loops in Python, ensure the following three components are included.
- Initialization part
- Conditional part
- Updation part (increment or decrement)
The purpose of a for loop is to retrieve or extract data from any iterable object.
- The keywords for, in, and else are used.
- varname is a programmer-defined variable.
- An iterable_object is any object containing multiple values, such as a sequence (string, tuple), list, set, or dictionary.
- The execution process of a for loop involves selecting each element from the iterable_object, assigning it to varname, and executing the block of statements. This process repeats for a finite number of times (equal to the length of the iterable_object) until all elements are processed.
- When all elements of the iterable_object are processed, the for loop condition becomes false. If an else block is present, its statements are executed, followed by other statements in the program.
- The else block is optional.
Note 1: For iterating over iterable objects, it is recommended to use a for loop.
Note 2: For repeating non-iterable objects, it is recommended to use a while loop.
A nested for loop is a for loop inside another for loop, where the inner loop runs completely for each iteration of the outer loop. With strings, nested for loops are used to
- Compare characters (e.g., finding duplicates).
- Generate patterns (e.g., printing substrings).
- Process combinations (e.g., anagrams or string matching).