Created
January 31, 2020 02:44
-
-
Save Excigma/6178df5356871d29eeae8d202f14e53b to your computer and use it in GitHub Desktop.
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
# Declare and initialise variables | |
# Prompt and collect the number the user wants to get the factorial of | |
userInput = input("Input a positive integer to calculate it's factorial: ") | |
factorial = 1 | |
# First try block tries to parse input as a float, | |
# Which allows decimal points, but throws (fails) when parsing letters, | |
# Such as "foo bar" | |
try: | |
# Check if it's numbers like 45 3424 34.5 | |
float(userInput) | |
# Second try block tries to parse input as a integer, | |
# Decimal points will fail here, and the except code will run | |
try: | |
# Check if it's numbers like 1 2 45 | |
# (Can also use modulus to check if number input is an integer) | |
# Which is probably better pratice than using a try | |
# https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number | |
# | |
userInput = int(userInput) | |
# Check if the user has inputted a number higher than 1 | |
if userInput >= 0: | |
# Input is correct, an integer and more than 0 | |
# Actually calculate factorial | |
for i in range (1, userInput + 1): | |
factorial = factorial * i | |
print("Factorial of ", userInput , " is: ", factorial) | |
else: | |
# Input is an integer, but less than 0 | |
print("Input must be positive") | |
except ValueError: | |
# Run if int(userInput) fails | |
print("Input must not contain decimals (must be a integer)") | |
except ValueError: | |
# Run if float(userInput) fails | |
print("Input must be a number") | |
# There's probably more comments than code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment