Last active
December 6, 2018 14:18
-
-
Save letsintegreat/7e6a1ed8ee04495fcd81855f4fe6811c to your computer and use it in GitHub Desktop.
Code written under an event called Google Code-in.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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