Welcome, guest | Sign In | My Account | Store | Cart

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.

#### 2 comments

Steven D'Aprano 10 years ago

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 `int` rather than `float`. So rather than repeat myself, I'll just ask you to read my comment there.

Hamid Sadeghi 8 years, 3 months ago

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.

# #

#### print("must be a number !!!")")

 Created by John on Sat, 8 Mar 2014 (MIT)

### Required Modules

• (none specified)