Finishing a program earlier, and not in a loop?

I am trying to make a short program that will return a factorial of a number that works fine. The only problem I encountered is that the program ends if the user enters a non-integer value.

num = input("input your number to be factorialised here!: ") try: num1 = int(num) except ValueError: print("That 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) 
+5
source share
2 answers

Decision

There are better ways to do this, but given the structure of the code, you can use else . See documents .

 num = input("input your number to be factorialised here!: ") try: num1 = int(num) except ValueError: print("That 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 is executed only if there are no exceptions.

suggestions

In order not to give away answers to your homework, here are some tips you should learn to clear your code:

  • Can you use range more efficiently? Hint: You can iterate over decreasing numbers by setting step to a negative integer.
  • Can you find a way to get rid of the num1 == 0 check?
+3
source

The OP actually asks how to abort the current execution of the script prematurely. An easy way to implement your idea is to use sys.exit() as

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

See the section for more details.

+3
source

Source: https://habr.com/ru/post/1275161/


All Articles