I need to find out the factorial number through user input, i have tried this way but answer show nothing here is my code:
Image show the Factorial code where i am facing the problem
I need to find out the factorial number through user input, i have tried this way but answer show nothing here is my code:
Image show the Factorial code where i am facing the problem
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))
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
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.
import math
print(math.factorial(int(input("enter the number"))))
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)