-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathAdreeja Ghatak
More file actions
33 lines (29 loc) · 849 Bytes
/
Copy pathAdreeja Ghatak
File metadata and controls
33 lines (29 loc) · 849 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
# wrote a program about factorial
adreeja/factorial.py
import sys
def factorial(n):
"""Iterative factorial: works for n >= 0"""
if n < 0:
raise ValueError("Negative numbers do not have factorials.")
result = 1
for i in range(2, n + 1):
result *= i
return result
def main():
# Usage:
# python factorial.py -> uses default n = 5
# python factorial.py 6 -> calculates factorial(6)
if len(sys.argv) > 1:
try:
n = int(sys.argv[1])
except ValueError:
print("Please provide a valid integer. Example: python factorial.py 6")
return
else:
n = 5 # default value for quick demo
try:
print(f"Factorial of {n} is {factorial(n)}")
except ValueError as e:
print(e)
if __name__ == "__main__":
main()