简体   繁体   中英

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?

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)

Taking for granted that 0! = 1 and 1! = 1, then you already have the two first numbers of your sequence. So you can multiply by num+1 to avoid multiplying by zero. Then you take your output before doing the next multiplication.

def fact(n):
    f=1
    for num in range(n+1):
        print(num,f)
        f=f*(num+1)
fact(5)
0 1
1 1
2 2
3 6
4 24
5 120

You can also create a lookup table if you want:

def fact(n):
    FACT=[]
    f=1
    for num in range(n+1):
        FACT += [f]
        f=f*(num+1)
    return FACT

F = fact(n)

F[0]
>>> 1

F[4]
>>> 24


  • range should start from 0 , hence range(0, n+1) or just range(n+1) because in your code the condition is never hit
  • when the condition is hit you should have a print : print(0, 0)
def fact(n):
    f=1
    for num in range(0,n+1):
        if num==0:
            print(num, num) # num is just 0
        else:
            f=f*num
            print(num,f)

Remarks:

  • the return is really needed? it is always 1 independently from n
  • 0! = 1 by definition. Maybe print(0, 1) ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM