Search code examples
pythonloopsfactorial

How to execute 0 when printing out the loop? I've been trying to print out the factorial in python. I need 0 to be printed in the output


    def fact(n):
        f=1
        for num in range(1,n+1):
            if num==0:
                return 1
            else:
                f=f*num
                print(num,f) 
    n=int(input())

fact(n)
#here is my code, but the output should be 
0 0
1 1
2 2
3 6
4 24
5 120
6 720
instead of 
1 1
2 2
3 6
4 24
5 120
6 720

Can you tell me what is wrong and what should I add to the code?


Solution

  • 0, 0 can't really be part of the factorial because then all following numbers would have to be multiplied by 0, making them all zero. I guess you could just print it out first.

    def fact(n):
        f=1
        print(0, 0)
        for num in range(1,n+1):
            
            f=f*num
            print(num,f) 
    n=int(input())
    fact(n)