Skip to content Skip to sidebar Skip to footer

Remove None From The Output Of A Function Call

def digits_plus(num): for i in range (num+1): print (str(i)+'+',end='') print (digits_plus(3)) Here's what I got returned: 0+1+2+3+None 'None' always exists at the l

Solution 1:

The reason this is happening to you is that you are printing the result of your function call, in this line here:

print(digits_plus(3))

But your function does not return any value, so it returns None. And None is being printed because you are telling Python to print it. (And it's on the same line as the rest because none of your other prints print a newline.) To solve this, change that line to just:

digits_plus(3)

Your function is doing the printing, so there is no need to also print the function's return value.

(You could also revise your function to return the desired value instead of printing it, which would make it more generally useful.)

Solution 2:

A more “Pythonic” solution, using str.join:

defdigits_plus(num):
    return'+'.join(str(i) for i inrange(num + 1))

>>> print(digits_plus(3))
0+1+2+3

While Python doesn't enforcecommand-query separation, it's generally considered best for a function to return a value xor perform a side effect (like printing), but not both. (Though, the standard library has exceptions to this rule, like list.pop.)

Also note the + 1 in the range call, since range does not include its upper bound.

Solution 3:

Your issue that digit_plus returns None by default. Using no return statement at all or just return will implicitly return None. So the easiest fix would be to just not print the result of digit_plus, and only calling it.

But this will still print a “+” at the end. To solve that use "+".join() like others suggested or add some logic to only add “+” if there are still items left. One way to do it is this way:

for i in range(num + 1):
    if i > 0:  # not the first timeprint("+", end="")
    print(i, end="")

In that case str(i) can be replaced by i as print() does it implicitly anyway.

Post a Comment for "Remove None From The Output Of A Function Call"