forked from OpenGuide/Python-Guide-for-Beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorial.py
More file actions
34 lines (21 loc) · 734 Bytes
/
Factorial.py
File metadata and controls
34 lines (21 loc) · 734 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
'''
This code asks the user to input a non-negative integer and then returns the factorial
'''
#Solicit user input until a non-negative integer is provided
while True:
try:
input_num = input("Enter a non-negative integer: ")
#The user should not enter a negative number or a non-integer
if (input_num<0) | (type(input_num)!=int):
print("Invalid entry\n")
continue
break
#The user should not enter anything else besides a non-negative integer (e.g. strings)
except Exception as e:
print("Invalid entry\n")
#Calculate the factorial expression as follows:
#1*2*...*input_num
result = 1
for i in xrange(1,input_num+1):
result*=i
print("{}! = {}".format(input_num, result))