Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Factorial Example

Python Factorial Example

Document Object Reference Manual Python3 Examples

The factorial of an integer is the product of all positive integers less than or equal to it; the factorial of 0 is 1. That is: n!=1x2x3x...xn.

Example

#!/usr/bin/python3

Filename : test.py

author by : www.runoob.com

Calculate the factorial from a number entered by the user

Get the number entered by the user

num

=

int

(

input

(

"

Please enter a number:

"

)

)

factorial

=

1

Check whether the number is negative, 0, or positive

if

num

<

0

:

print

(

"

Sorry, negative numbers have no factorial

"

)

elif

num

==

0

:

print

(

"

The factorial of 0 is 1

"

)

else

:

for

i

in

range

(

1

,

num

1

)

:

factorial

=

factorial

i

print

(

"

The factorial of %d is %d

"

%

(

num

,

factorial

)

)

The output of the code above is:


请输入一个数字: 3
3 的阶乘为 6

Document Object Reference Manual Python3 Examples