Python newbie weird output

The code I posted below works accordingly to my expectations except for 1 problem. When it goes into the factorial route, after the number is determined as a prime number, ill see for example: 2! = 2none. The “none” here is the problem, but I have no idea where and what is causing that “none” to appear here. If there’s any suggestions or solutions, I would really appreciate it!

def getSum(number): 
    sum = 0
    for digit in str(number):  
      sum += int(digit)       
    return sum

def factorial():
    if(number<0):
        print("invalid input")
    elif ((number==0) or (number==1)):
        print(number,end="! = 1")
    else:
        factorial=1
        for i in range(1, number+1):
            factorial=factorial*i
        print(number,end="! = "+ str(factorial))


number=int(input("enter number:")) #Q13
if(number==2):
    print("A prime number")
    print(factorial())
elif((number<2) or (number%2==0)):
    print("not prime number")
    print(getSum(number))
else:
    for i in range (2, number):
        if (number%i==0):
            print("Not prime number")
            print(getSum(number))
            break
        if (i==number-1):
            print("A prime number")
            print(factorial())
        

This line is the reason: It writes the return value of the factorial() function to standard output. There is no explicit return statement in the function, so the return value is None.

There are a number of other issues with the factorial() function:

  • It uses the global variable number instead of a parameter.

  • Don’t use the end parameter to print() for data. Instead better return the calculated value and format the result.

  • If the parameter number is invalid, the function should raise an error instead of just writing a message.

Ah thanks man, got it fixed up!

1 Like