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)
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.
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:
step
to a negative integer.num1 == 0
?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With