Nested loops

In Python, it is possible to implement a loop within a loop. For example, let's say we have to print x and y coordinates of a map. We can use nested loops to implement this:

for x in range(0,3): 
for y in range(0,3):
print(x,y)

The expected output is:

Be careful about code indentation in nested loops as it may throw errors. Consider the following example:

for x in range(0,10): 
for y in range(0,10):
print(x,y)

The Python interpreter would throw the following error:

    SyntaxError: expected an indented block

This is visible in the following screenshot:

Hence, it is important to pay attention to indentation in Python (especially nested loops) to successfully execute the code. IDLE's text editor automatically indents code as you write them. This should aid with understanding indentation in Python.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.27.232