Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mona Jalal
4,302 PointsHow can I fix this type error in recursive program?
''' Write a function that takes an integer n and returns the nth iteration of the fractal known as Sierpinski's Gasket. Here are the first few iterations. The fractal is composed entirely of L and white-space characters; each character has one space between it and the next (or a newline).
0
L
1
L
L L
2
L
L L
L L
L L L L
3
L
L L
L L
L L L L
L L
L L L L
L L L L
L L L L L L L L
def sierpinski(n):
if n==0:
return "L"
print(sierpinski(n-1)+"\n"+sierpinski(n-1)+" "+sierpinski(n-1))
sierpinski(1)
sierpinski(2)
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/mona/PycharmProjects/PythonCodes/sierpinski.py L Traceback (most recent call last): L L File "/Users/mona/PycharmProjects/PythonCodes/sierpinski.py", line 38, in <module> L sierpinski(2) L L File "/Users/mona/PycharmProjects/PythonCodes/sierpinski.py", line 34, in sierpinski print(sierpinski(n-1)+"\n"+sierpinski(n-1)+" "+sierpinski(n-1)) TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Process finished with exit code 1
2 Answers
Steven Parker
243,656 Points
For values higher than 0, your function prints but does not return anything.
So when you call it with 2 or more, it tries to construct a string using recursive calls that return nothing ("None").
Mona Jalal
4,302 PointsI am looking for complete answer in Python