Just a simple factorial program I made in Python 3.
Python, 14 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14
def fact(): number=eval(input("Enter a number to get the factorial: ")) initialvalue=1 if number>0: for number in range(number,1,-1): initialvalue=initialvalue*number print(initialvalue) elif number==0: print(1) elif number<0: for number in range(number, -1, 1): initialvalue=initialvalue*number print(-initialvalue) fact()
Should work with positive and negative numbers. Returns 1 for the factorial of 0 as it should.
You make the very common mistake of using
eval()on untrusted input. Just about everything I write here: http://code.activestate.com/recipes/578847-simple-derivative-solver-in-python/?in=lang-python#c1 applies to your code as well, except you should use
float. So rather than repeat myself, I'll just ask you to read my comment there.
I have a code too but just in 12 lines, and it works for any input, integer, float,and strings.and also I suppose 0!= 0 and for float numbers it calculate the factorial of it's integer part of the decimal number and for strings it prints some warning.
result = 1
if n == 1 or n== -1 or n==0:
result = n
result = n * factorial(n-int((n/abs(n))))
n=int(float((input("Enter a number to get the factorial: "))))
print("must be a number !!!")")