0

I need to find out the factorial number through user input, i have tried this way but answer show nothing here is my code:

enter image description here

Image show the Factorial code where i am facing the problem

Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
Golam Rabbani
  • 55
  • 1
  • 7

5 Answers5

2

Please Remove Line 2 on code:

def factorial(n):

    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
n = int(input("enter the number"))#python 3.x
print(factorial(n))
Community
  • 1
  • 1
Mr Singh
  • 3,936
  • 5
  • 41
  • 60
1

You can use math library in python.

import math

def factorial():
    n= int(input("enter a number"))
    print("Factorial of number ", math.factorial(n))

factorial()

Or

def factorial():
    n = int(input("enter a number:"))
    factorial = 1
    if n == 0:
        print("The factorial of 0 is 1")
    else:
       for i in range(1,n + 1):
           factorial = factorial*i
       print("The factorial of number:",factorial)  

You can also add a check for number below 0 and use elif .
Or,

def factorial(n):

    if n == 0:
        return 1
    else:
        return n * factorial(n-1)  
n = int(input("enter the number"))  
print(factorial(n))   

Inputs by default is String, You need to convert it to int

Manjunath Rao
  • 3,790
  • 3
  • 12
  • 18
1

You are attempting to implement recursion in a loop where the input is always given by the user. This causes your recursive setup to act differently than expected. Instead you can implement it as follows

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
n = int(input("enter the number"))# for python3.x
print(factorial(n))

Now that n = input("enter the number") is outside the recursive loop it is only called once and n is not externally updated during the recursion.

Mr Singh
  • 3,936
  • 5
  • 41
  • 60
Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32
1
import math
print(math.factorial(int(input("enter the number"))))
0xC0000022L
  • 20,597
  • 9
  • 86
  • 152
  • 1
    While this is a nice two-liner, it's not very Pythonic. Also you may want to *explain* why your solution is the answer. – 0xC0000022L Oct 29 '18 at 15:37
1

By for:

num=int(input("Enter The Number to show it factorial:"))
fact=1
for x in range(1,num+1):
     fact*=x
print("the factorial of this number is({})".format(fact))

By while:

n=int(input("Enter The Number:"))
x=1
fact=1
while(x<=n):
     fact*=x
     x+=1
     print(fact)
SaLeH
  • 11
  • 4