I have the following code:
def letterPyramid(letter, rows):
count = rows
if rows == 0:
return
elif letter.isupper():
return
else:
return str(letterPyramid(letter, rows-1)) "\n" letter*count
pass
y = letterPyramid("a", 6)
print(y)
This outputs:
None
a
aa
aaa
aaaa
aaaaa
aaaaaa
Everything is right in the output except it returns None
first. How do I prevent None
from printing at the top of the pyramid?
CodePudding user response:
When rows == 0
, you aren't explicitly returning any value, which means that your function is implicitly returning None
.
You know that at the first level, you only need to print out one letter. So, make rows == 1
your base case, rather than rows == 0
. (Treating zero as the base case will print an extraneous leading newline in the resulting string.)
def letterPyramid(letter, rows):
if rows == 1:
return letter
else:
return letterPyramid(letter, rows - 1) "\n" letter * rows
y = letterPyramid("a", 6)
print(y)
This outputs:
a
aa
aaa
aaaa
aaaaa
aaaaaa
CodePudding user response:
In python, functions and methods return None
implicitly, by default, so if you just say return
, or don't say return
at all, that's what happens.
There are two places where your recursive function does this:
def letterPyramid(letter, rows):
count = rows
if rows == 0:
return # implicitly returns `None`
elif letter.isupper():
return # implicitly returns `None`
else:
return str(letterPyramid(letter, rows-1)) "\n" letter*count
y = letterPyramid("a", 6)
print(y)
The None
at the top of your pyramid is generated when the inner-most iteration is run and if rows == 0
evaluates to True
.
To prevent this, you can return an empty string, which will concatenate with the rest of your output without issue. However, just doing this still leaves an empty line above the pyramid. This is easily removed using .lstrip()
on the final string before assignment.
def letterPyramid(letter, rows):
count = rows
if rows == 0:
return ''
elif letter.isupper():
return
else:
return str(letterPyramid(letter, rows-1)) "\n" letter*count
y = letterPyramid("a", 6).lstrip()
print(y)
CodePudding user response:
When your functions returns without a value:
if rows == 0:
return
It returns None
. This is why you're seeing None
printed, because the following adds it to the string.
return str(letterPyramid(letter, rows-1)) "\n" letter*count
Specifically:
str(letterPyramid(letter, rows-1))
A better approach would be two have an exit condition at 1
rather than 0
. This will avoid a needless newline character being added to the top of the pyramid.
def pyramid(lines, ch='*'):
if lines == 1:
return ch
elif lines < 1:
return ''
else:
return f"{pyramid(lines-1, ch)}\n{ch * lines}"
>>> print(pyramid(4))
*
**
***
****
>>>