Why is None getting printed, even if the return value isn't None (It happens only for the else condition)

Viewed 42
def armstrong(x):
    number = str(x)
    length = len(number)
    sum=0
    for i in number:
        sum = sum + pow(int(i),length)

    print("Yes {0} is an Armstrong Number" .format(x) if(sum==x) else print("No {0} is not an Armstrong Number" .format(x)))   

    return 0


num=int(input("Enter a Number: "))
armstrong(num) 

For a non armstrong number the output comes along with a None, could someone please explain the reason behind it. I've attached the output as an image link for the same.

log

1 Answers

You have a print within another print, and since print always returns None, that's what you're printing. I'm guessing this is what you need:

print("Yes {0} is an Armstrong Number".format(x) if(sum==x) else "No {0} is not an Armstrong Number".format(x))

P.S try not to use the word sum because you're shadowing a built-in function

Related