Skip to content

Instantly share code, notes, and snippets.

@letsintegreat
Last active December 6, 2018 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letsintegreat/7e6a1ed8ee04495fcd81855f4fe6811c to your computer and use it in GitHub Desktop.
Save letsintegreat/7e6a1ed8ee04495fcd81855f4fe6811c to your computer and use it in GitHub Desktop.
Code written under an event called Google Code-in.
# Method to calculate factorial of the number passed as a parameter using recursion.
def fact(num):
if num <= 1:
return 1
return num * fact(num - 1) * 1.00
try:
print('Enter a number: ') # Message to display on screen
# I'm casting the entered string into float because if the entered number is 5.0 then it raises a ValueError,
# which should not happen in this case. So, I'm using float()
num = float(input())
if num < 0: # Condition to check if the entered number is smaller than 0
raise ValueError
if num % 1 != 0: # Condition to check if the entered number have some decimal digits
raise ValueError
print(f'\nFactorial: {fact(num):.2f}') # Using f-string formatting to show 2 decimal places
except ValueError:
"""
This will handle situations when users have entered
- any string
- any number smaller than 0
- any number with decimal places.
"""
print('\nOnly numbers greater than or equal to 0, with no decimal digits are accepted')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment