5

I'm attempting to make a short program that will return the factorial of a number, which works fine. The only problem I am having is getting the program to end if the user inputs a non-integer value.

num = input("input your number to be factorialised here!: ")

try:
    num1 = int(num)
except ValueError:
    print("That's not a number!")



if num1 < 0:
    print("You can't factorialise a negative number")
elif num1 == 0:
    print("the factorial of 0 is 1")
else:
        for i in range(1,num1+1):
            ans = ans * i
        print("the factorial of", num, "is", ans)
paisanco
  • 4,098
  • 6
  • 27
  • 33
Amy Fawcett
  • 107
  • 5
  • 2
    You need to define `ans` – Matt Hall Feb 04 '18 at 16:19
  • Possible duplicate of [How to check if string input is a number?](https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) – itsmrbeltre Feb 04 '18 at 16:26
  • why are you asking such questions before previously researching here itself? it has been answer too many times: https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number, https://stackoverflow.com/questions/19440952/how-do-i-check-if-raw-input-is-integer-in-python-2-7, http://www.101computing.net/number-only/ --> this is not a homework solving tool. – itsmrbeltre Feb 04 '18 at 16:27
  • You could use regex too. – Anton vBR Feb 04 '18 at 16:30

2 Answers2

4

Solution

There are better ways of doing this but given your code structure you can use else. See the docs.

num = input("input your number to be factorialised here!: ")

try:
    num1 = int(num)
except ValueError:
    print("That's not a number!")
else:
    if num1 < 0:
        print("You can't factorialise a negative number")
    elif num1 == 0:
        print("the factorial of 0 is 1")
    else:
        ans = 1
        for i in range(1,num1+1):
            ans = ans * i
        print("the factorial of", num, "is", ans)

The else clause only executes if no exceptions are thrown.

Suggestions

So as not to give away answers to your homework, here are a couple suggestions that you should take a look at to clean up your code:

  1. Can you use range more efficiently? Hint: you can iterate over decreasing numbers by setting the step to a negative integer.
  2. Can you find a way to get rid of the check num1 == 0?
Alex
  • 18,484
  • 8
  • 60
  • 80
3

The OP is actually asking how to terminate the current script execution prematurely. The straightforward way to implement your idea is to use sys.exit() like

try:
    num1 = int(num)
except ValueError:
    sys.exit()

For more details, see this thread.

Lingxi
  • 14,579
  • 2
  • 37
  • 93
  • 1
    It's a fairly trivial point, but using a non-zero exit status here might be slightly more proper. – Nathan Vērzemnieks Feb 04 '18 at 18:07
  • I agree this causes the program to exit, but adding an `else` clause (or some other form of error handling) is the proper way to handle this. – Alex Feb 15 '18 at 17:43