1

I need help with my recursion code below. The code is suppose to print out an * followed by an i for every n. I realize that my base case might be incorrect and that it might be the reason for the string quotes in the output, but when I try to set the base case to return 0 or n, I get the error stating that I cannot convert integer into string implicitly.

def printPattern(n):  

    if n == 0:
        return('')
    else:
        return('*' + printPattern(n-1) + 'i')

My output:

>>> printPattern(3)  
'***iii'

Output I need (without the string quotations):

>>> printPattern(3)  
***iii

Any ideas? Am I using the wrong logic here? Should I be going a different path with my code or is there anyway I can format the output to remove the string quotations?

2
  • 3
    Use print printPattern(3) Commented Feb 15, 2013 at 9:29
  • We're here to help those that manage to state their questions right :) Don't forget to accept (click the checkmark) the answer you feel answers your question best :) Commented Feb 15, 2013 at 9:55

2 Answers 2

2

You're likely seeing the quotes simply because the interactive shell is showing you a str type thing. try

>>> print printPattern(3)

which will actually print the pattern, rather than just return it (or, in python 3, use print(printPattern(3)) as a function).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you much, that helped and gave me the output I needed.
2

Your function is building a string and returning it. When running in an interactive shell and calling a function, Python will print the representation (repr) of the element. For a string, the repr includes quotation.

You just have to print the result.

If instead you want your function to do the printing, you'll have to modify it. The easiest way would be to use an inner private function to build the string, and use a print statement at the end.

def printPattern(n):
    def buildPattern(n):
        if n == 0:
            return('')
        else:
            return('*' + buildPattern(n-1) + 'i')
    print(buildPattern(n))

BTW, you probably don't want to use recursion for that function as Python does not optimize recursive call, and has a pretty low recursion limit (the call stack is by default limited to a height of a thousand or so).

1 Comment

I appreciate the help, and the reason I am doing it using recursion is to get better at coding. I am going through a Python book right now and that is one of the problems.

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.