Yes, both while loops can be nested within for loops and vice versa in Python. Nesting loops means placing one loop inside another. This is a common programming practice when you need to iterate over elements in a nested structure, such as a list of lists or a matrix.
Here's an example of a while loop nested within a for loop:
for i in range(3):
print(f"Outer loop iteration {i}")
j = 0
while j < 2:
print(f" Inner loop iteration {j}")
j += 1
And here's an example of a for loop nested within a while loop:
i = 0
while i < 3:
print(f"Outer loop iteration {i}")
for j in range(2):
print(f" Inner loop iteration {j}")
i += 1
In both cases, the indentation is crucial in Python to define the scope of the loops. The inner loop is indented and considered part of the outer loop based on the indentation level.
0 Comments:
Post a Comment