Search code examples
pythonloopsfactorialfloating

How can i stop my python program from crashing


I wrote a program to calculate the factorial of a number all work perfectly but crashes when for test I enter a float number. My goal is for a floating number to be accepted but not calculated. As the program will accept but return something like "Bad entry, only integers are accepted." I have tried multiple statement but it only work for the number I put in the statement. So I thought maybe something should be built, maybe by naming some floats and doing some sort of subtraction. But I get lost. here is the program I have so far without the floating statement included:

    def main():
# take input from the user
        num = int(input("Enter a number: "))
        factorial = 1
        if num > 100:
            print("Bad entry. It should be an integer less than or equal to 100!")
            print("Please try again: ")
        elif num == 0:
            print("The factorial of 0 is 1")
        elif num < 0:
            print("Bad entry. It should be an integer superior than or equal to 0!")
            print("Please try again: ")  
        else:
            for i in range(1,num + 1):
                factorial = factorial*i
            print("The factorial of",num,"is",factorial)

main()

Solution

  • def main():
        # take input from the user
        num = float(input("Enter a number: "))
        if (num%1 != 0):
            print("Bad entry, only integers are accepted.")
            return 
    
        num = int(num)
        factorial = 1
        if num > 100:
            print("Bad entry. It should be an integer less than or equal to 100!")
            print("Please try again: ")
        elif num == 0:
            print("The factorial of 0 is 1")
        elif num < 0:
            print("Bad entry. It should be an integer superior than or equal to 0!")
            print("Please try again: ")  
        else:
            for i in range(1,num + 1):
                factorial = factorial*i
            print("The factorial of",num,"is",factorial)
    
    main()