Input
[['1','2','3'],['a','b','c'],['6','7','8'],['e','f','g']]
Output should be:
1, 2, 3 a, b, c 6, 7, 8 e, f, g
Code:
def print_row(los):
print ', '.join(los)
def print_table(los):
lose = []
if los == []:
return
else:
return print_row(los[0]) + print_table(los[1:])
Currently:
print_table([['1','2','3'],['a','b','c'],['6','7','8'],['e','f','g']])
Gives:
1, 2, 3 a, b, c 6, 7, 8 e, f, g TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
How do I fix this?
Your function returns
None(an emptyreturnstatement). Return an empty string instead:You also have a
losedefinition there that is never used, and you can test for the empty list withnot los. Last but not least, sincereturnexits the function early, theelse:statement is optional.Next,
print_row()returnsNoneas well, since you don’t return anything from it. Simply discard it’s return value:Note that you never use the return value of
print_tableanyway, so you may as well not return anything; simply test if there is anything to print:Now you can just inline the
print_rowfunction (which is just a one-liner):This is still recursive; Python isn’t that strong at recursion, but it can do looping very well:
which can be reduced to a join on newlines too: