Skip to content

Instantly share code, notes, and snippets.

@grze2000
Created October 28, 2018 18:24
Show Gist options
  • Save grze2000/c6bc71aec388e2ea2250ed0bab534256 to your computer and use it in GitHub Desktop.
Save grze2000/c6bc71aec388e2ea2250ed0bab534256 to your computer and use it in GitHub Desktop.
Calculating the factorial value of a given number
from decimal import *
import sys
setcontext(Context(prec=3,capitals=0))
inputValue = input("Enter n: ") # Enter the value of n
try:
integer = int(inputValue) # Convert a string to an integer
if(integer >= 0): # If the integer is non-negative
factorialValue = Decimal(1) # Set the initial value
for i in range(1,integer+1): # For every positive integer less than n
factorialValue *= i # Multiple the value by the integer
if(factorialValue > sys.float_info.max): # If the factorial value is greater than maximum float value...
print("Factorial value:", factorialValue) # ...display value in the E-notation
else:
print("Factorial value: {0:.2f}".format(float(factorialValue))) # Otherwise, display value as float with 2 decimal places
else:
print("Entered value is not a natural number!") # Show error if the integer is negative
except ValueError:
print("Entered value is not a natural number!") # Show error if string is not an integer
except Overflow:
print("Overflow Error: Value is too large!") # Show error if value is to large for Decimal module
except:
print("Unknown error!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment