简体   繁体   中英

Beginner with a problem using recursion in Python

The exercise is to create a recursive function that accepts another function and an argument. I've encountered an semantic error, and my function is not doing what I had hoped it would do. I'm a beginner, so this may be a very easy fix, but I can't seem to find it. Thank you for any help you can provide:

def do_this(func, arg):   # this function will call another function (func) a maximum of (arg) times
                          
    arg -= 1              # in order to ensure that we call (func) only (arg) times, I reduce (arg) by 1 
                           #to start
    if arg <= 0:
        return
    else:
        do_this(func, arg) # here is where the recursion takes place when this function calls itself - if 
                           # this is written correctly, then this function will call itself (arg) times


def print_n(s, n):        # this function is also recursive, it will print the arguments passed to it 
                          #from the function 'do_this'
      if n <= 0:          # each time it completes a cycle of 'n' iterations it will print the bundle 
                          #number
        x = 1
        print("Bundle Number", x)
        x += 1
        return
      else:
        print(s)
        print_n(s, n - 1)

do_this(print_n("hello", 2), 4)

This should print the following:

hello
hello
Bundle Number 1
hello
hello
Bundle Number 2
hello
hello
Bundle Number 3
hello
hello
Bundle Number 4

do_this calls itself but never actually calls func .

Also, you shouldn't pass parameters to print_n before passing it to do_this - you should pass the function itself along with all the data you need to perform the calls. Passing parameters will cause the call to print_n to be actually executed. Normally, the return value of print_n would then be passed to do_this , except that there is no return value.

Remember, you want to pass print_n itself to do_this , not just the result of print_n .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM