我的代码有什么问题,请检查我的代码?

扎眼的阳光 python 384

原文标题What is wrong with my code, Please check my code?

a = int(input())
if (a==0 or a==1 or a<1):
  print("factorial is one") 
else:
  fact =1
  while(a>1):
   fact = fact *a
   a = a-1
   print("factorial:",fact)

和输出就像:6factorial:6factorial:30factorial:120factorial:360factorial:720

但我只想要720

原文链接:https://stackoverflow.com//questions/71476966/what-is-wrong-with-my-code-please-check-my-code

回复

我来回复
  • gaetan1903的头像
    gaetan1903 评论

    压痕问题,在外面做打印while

    a = int(input())
    if (a==0 or a==1 or a<1):
      print("factorial is one") 
    else:
      fact =1
      while(a>1):
       fact = fact *a
       a = a-1
      print("factorial:",fact)
    

    N.B:the best way to do a factorial, is use a recursive function

    def fact(n):
      if n == 1:
        return 1
      else:
        return n * fact(n-1) 
    
    
    number = int(input('Your nuumber'))
    
    print('factorial', fact(number))
    
    2年前 0条评论