0

I have just started to program in python, and I am stuck with a problem regarding recursion.

The program seems to compile, however, the print output is not shown.

Here is the program:

print 'type s word'
s = raw_input()
print 'enter a number'
n = raw_input()

def print_n(s, n):

 if n<=0:
  return 
 print s
 print_n(s, n-1)

the output i get is:

xxxx@xxxx-Satellite-L600:~/Desktop$ python 5exp3.py
type s string
hello
add the number of recursions
4
xxxx@xxxx-Satellite-L600:~/Desktop$

What is wrong, and how can I get the program to show an output?

5
  • 6
    I recommend using more than one space for your indentation level. Commented Oct 31, 2012 at 20:16
  • The code you show doesn't actually call the recursive function... if it did you would get an exception as raw_input returns strings which you must convert to integers with int. Commented Oct 31, 2012 at 20:17
  • You should also use return print_n(s, n-1), when calling the function recursively, though it might not cause any problem in this case, but keep that in mind for future uses. Commented Oct 31, 2012 at 20:23
  • @AshwiniChaudhary: That seems unnecessary here. Commented Oct 31, 2012 at 20:33
  • @StevenRumbalski yes I mentioned that, I just wanted to tell the OP that it can be useful when he's returning values from function, instead of just printing, coz in that case the function will return None. Commented Oct 31, 2012 at 20:56

2 Answers 2

5

Your posted code defines the function print_n but never calls it. After the function definition place a print_n(s, n).

Once you do this you'll find some errors caused by the fact the n is currently a string (raw_input returns a string). Use int(a_string) to convert a string to an integer. Calling your function like this will solve the issue

print_n(s, int(n))

Or do

n = int(raw_input())

The complete code:

s = raw_input('type a word: ')
n = int(raw_input('enter a number: '))

def print_n(s, n):
    if n <= 0:
        return 
    print s
    print_n(s, n-1)

print_n(s, n)
Sign up to request clarification or add additional context in comments.

Comments

2

try n = raw_input() -> n = int(raw_input())

1 Comment

You are correct that n needs to be an integer, but the initial issue is that he never calls the print_n. Otherwise, he would have received TypeError on the first recursion. (It would not have exited early because "string" <= 0" evaluates to False in Python 2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.