Python Forum
Print name N times using recursion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Print name N times using recursion (/thread-21972.html)



Print name N times using recursion - ift38375 - Oct-23-2019

How can i write program to Print "Hello" 5 times using recursion.

I am trying code below but it is not working.
def fnc():
    for i in range(5):
     print("Hello")
    fnc()
    

fnc()    



RE: Print name N times using recursion - SouthernYankee - Oct-23-2019

Not sure why you are calling func() inside the function, but this worked for me:

def func():
    for i in range(5):
        print ("Hello")

func()
Maybe your IDE is detecting an infinite loop? Your current code will cause a stack overflow.


RE: Print name N times using recursion - buran - Oct-23-2019

(Oct-23-2019, 05:31 AM)SouthernYankee Wrote: Not sure why you are calling func() inside the function
Note that OP assignment is asking them to use recursion... They try to do that although unsuccessfully as they end up with infinite recursion


RE: Print name N times using recursion - SouthernYankee - Oct-23-2019

(Oct-23-2019, 05:34 AM)buran Wrote: Note that OP assignment is asking them to use recursion... They try to do that although unsuccessfully as they end up with infinite recursion

Ah. Didn't catch that this was a homework assignment. Makes since now. Still getting used to this forum. I'll be more careful in the future.


RE: Print name N times using recursion - ichabod801 - Oct-23-2019

You need to get rid of the loop, just print one time per function call. Then you need a terminating condition that stops the recursion. You would typically pass the value that terminates as a parameter to the function, and modify it each time you make the recursive call.


RE: Print name N times using recursion - ift38375 - Oct-23-2019

(Oct-23-2019, 01:35 PM)ichabod801 Wrote: You need to get rid of the loop, just print one time per function call. Then you need a terminating condition that stops the recursion. You would typically pass the value that terminates as a parameter to the function, and modify it each time you make the recursive call.

Please share code for this program ...


RE: Print name N times using recursion - jefsummers - Oct-23-2019

Eliminate the for loop, add a parameter to fnc() that will be the counter. In the function increment the counter, print the name, do a test to see if the parameter is now 5, and call fnc(x) again if it is not.

Will guide but not write your homework assignment


RE: Print name N times using recursion - ichabod801 - Oct-23-2019

(Oct-23-2019, 02:24 PM)ift38375 Wrote: Please share code for this program ...

Please try to code this program yourself, and if it doesn't work I will help you fix it.