[SOLVED] How do I create nested for loops inside a function?

Issue

I am trying to create a function that will take an input x and create x nested for loops. Here’s an example:

def looper(loop_amount, loop_value):
    for n in range(loop_amount):
        # Create a nested loop with loop_value.

looper(3, 5)

# Creates this:
for n in range(5):
    for n in range(5):
        for n in range(5):

Solution

A possible (though maybe non-pythonic) solution is to use recursion:

def looper(loop_amount, loop_value):
    if loop_value == 0:
        # Code to be run in innermost loop
    else:
        for n in range(loop_amount):
            looper(loop_value - 1)

This can be extended to access each loop’s index, or have a return value in some fashion.

Answered By – Sponja

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *