Home > Blockchain >  How to ignore printing "None Object" in python
How to ignore printing "None Object" in python

Time:08-13

n = int(input())

def reverse(num):
    while num > 0:
        return f"{num}{reverse(num - 1)}"

result = reverse(n)
print(result)

I have some code lines as above. (Incase Input n = 5)It prints "54321None" instead of "54321" as I expected. Please help me

CodePudding user response:

The last iteration will always be a 0. If you just call reverse(0) it will return None, so that is the problem. Without rewriting too much code the 'simple' solution could be:

return f"{num}{reverse(num-1)if num-1 != 0 else ''}"

This only executes the reverse function if the variable you pass into reverse is not 0. Otherwise it will return Nothing.

  • Related