By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,493 Members | 1,302 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,493 IT Pros & Developers. It's quick & easy.

using recursion

P: 6
new to python and I have this assingment: I need to write a recursive function that takes paramaters (aString,nTimes) and it needs to print the aString parameter the number of times specified by nTimes. I cannot use a for or while loop, just recursion. How would I go about doing this? all i know how to do is get it started and use recursion to call function again.

def printNtimes(aString,nTimes):

I also know how to do it using recursion with one parameter:
Expand|Select|Wrap|Line Numbers
  1. def n_lines(n):
  2.       if n>0:
  3.           print "Line"
  4.           n_lines(n-1)
Jul 24 '07 #1
Share this Question
Share on Google+
2 Replies


bartonc
Expert 5K+
P: 6,596
new to python and I have this assingment: I need to write a recursive function that takes paramaters (aString,nTimes) and it needs to print the aString parameter the number of times specified by nTimes. I cannot use a for or while loop, just recursion. How would I go about doing this? all i know how to do is get it started and use recursion to call function again.

def printNtimes(aString,nTimes):

I also know how to do it using recursion with one parameter:
Expand|Select|Wrap|Line Numbers
  1. def n_lines(n):
  2.       if n>0:
  3.           print "Line"
  4.           n_lines(n-1)
It's just the same; no big change:
Expand|Select|Wrap|Line Numbers
  1. def n_lines(anStr, n):
  2.       if n>0:
  3.           print anStr
  4.           n_lines(anStr, n-1)
  5.  
  6.  
  7. n_lines("hello", 5)
To learn how to do the pretty printing (which I've added to your post), please read the "REPLY GUIDELINE" on the right hand side of the page while you reply. They are required under the rules of our Posting Guidelines. Thanks
Jul 24 '07 #2

bvdet
Expert Mod 2.5K+
P: 2,851
It's just the same; no big change:
Expand|Select|Wrap|Line Numbers
  1. def n_lines(anStr, n):
  2.       if n>0:
  3.           print anStr
  4.           n_lines(anStr, n-1)
  5.  
  6.  
  7. n_lines("hello", 5)
To learn how to do the pretty printing (which I've added to your post), please read the "REPLY GUIDELINE" on the right hand side of the page while you reply. They are required under the rules of our Posting Guidelines. Thanks
A very minor change:
Expand|Select|Wrap|Line Numbers
  1. def n_lines(anStr, n):
  2.       if n:
  3.           print anStr
  4.           n_lines(anStr, n-1)
Jul 24 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.