Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ending a program early, not in a loop?

Tags:

python

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)
like image 985
Amy Fawcett Avatar asked Feb 04 '18 16:02

Amy Fawcett


2 Answers

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?
like image 147
Alex Avatar answered Oct 05 '22 06:10

Alex


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.

like image 29
Lingxi Avatar answered Oct 05 '22 06:10

Lingxi