Loops_and_Iteration
Loops_and_Iteration
Loops and Iteration: Loops are used to execute a block of code repeatedly. They
are essential for iterating over data structures or for performing repetitive tasks.
Let us discuss types of Loops and iterations:
for loop: The for loop is used to iterate while loop: The while loop continues
over a sequence (e.g., lists, strings) and execution while a specified condition
execute a block of code for each item in remains True.
the sequence.
This code defines a string "Data" and The code initializes count to 1, then uses
then uses a for loop to iterate through a while loop to print values from 1 to 3
each character in the string, printing (inclusive), incrementing count with
each character one at a time. each iteration, resulting in the output "1,
2, 3".
Loop control statements (break and Nested loops: Nested loops involve
continue): using loops within loops for complex
● break is used to exit a loop iterations.
prematurely.
● continue is used to skip the rest of
the current iteration and proceed to
the next one.
1|P a g e
Example Code: Example Code:
# Using 'break' to exit the loop
prematurely i = 1
count = 1 while i <= 2:
while count <= 5: j = 1
print("Current count:", while j <=2:
count)
print(i, "x", j, "=", i *
if count == 3: j)
break # Exit the loop j += 1
when count is 3
i += 1
count += 1
print('\n')
Output:
Current count: 1
Current count: 2 Output:
Current count: 3 1 x 1 = 1
Current count: 1 1 x 2 = 2
Current count: 2
Current count: 4 2 x 1 = 2
Current count: 5 2 x 2 = 4
The first part of the code uses break to This code prints a custom
exit the loop when count is 3, and the multiplication table pattern for
second part uses continue to skip numbers 1 and 2, displaying the results
printing when count is 3. in a 2x2 grid.
2|P a g e
Range Function
The range() function generates a sequence of integers, commencing at 0 by
default and incrementing by 1, concluding before a specified value.
Example Codes:
3|P a g e