Saturday 18 November 2023

Can a while loop be nested within a for loop and vice versa?

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.


Post a Comment

Popular Posts


AI (1) Android (23) AngularJS (1) Assembly Language (2) book (1) Books (35) C (76) C# (12) C++ (82) Course (51) Coursera (8) Cybersecurity (4) Data Science (19) Data Strucures (4) Deep Learning (4) Django (1) Downloads (3) edx (1) Engineering (13) Excel (1) flutter (1) FPL (17) Google (10) Hadoop (1) HTML&CSS (41) IBM (1) IS (25) Java (90) Leet Code (4) Machine Learning (2) Meta (2) Pandas (2) PHP (20) Projects (26) Python (584) Python Coding Challenge (37) R (69) Selenium Webdriver (2) Software (15) SQL (28)


Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses