If you want to ensure it's a positive integer, and if you want to keep asking for input as specified in your question, you'll need a few more control structures:
from math import factorial
def get_input():
while True:
try:
inp = int(input("Enter a positive integer> "))
if inp < 0:
raise ValueError("not a positive integer")
except ValueError as ve:
print(ve)
continue
break
return inp
print(factorial(get_input()))
This works by just trying to convert the input to an integer, and retrying if this fails. The continue
statement is used to skip past the break
. The try/except
structure catches the error if it's not an integer, or the error explicitly raised if it's less than 0. It also uses the as
feature of except
to print a better indication of the error. It's encapsulated in a function to make things easier - I find factorial(get_input())
to be pretty expressive, with the added bonus of being more reusable.
This currently doesn't end when the user input is 0
, as 0
is a perfectly valid input for factorial
, although it should be easy enough to adapt to this with an if
statement.
This program might be used like this:
Enter a positive integer> abc
invalid literal for int() with base 10: 'abc'
Enter a positive integer> 0.2
invalid literal for int() with base 10: '0.2'
Enter a positive integer> -5
not a positive integer
Enter a positive integer> 6
720
By the way, this code works according to EAFP - it just tries to convert to an integer, and handles failure. This is more idiomatic Python than first trying to determine if it could be an integer (LBYL).
If you're using Python 2, you'll need to change input
to raw_input
.