def factorial(n):
if isinstance(n,int):
if n == 1:
return 1;
elif n <= 0:
print("Factorial is for positive integer.")
else:
return n*factorial(n-1)
else:
print("It's only for integers")
factorial_number = input("give an integer that you want to factor: ")
print(factorial(factorial_number))
Asked
Active
Viewed 39 times
-7

NoobDude
- 3
- 2
-
3`input` returns a string regardless of what you type. – meowgoesthedog Mar 08 '19 at 13:24
-
1Maybe read the python docs about ``input``? – Mike Scotty Mar 08 '19 at 13:24
-
input is returning a string, you need to typecast it as needed, (to int, im guessing here) – Paritosh Singh Mar 08 '19 at 13:25
2 Answers
0
The built-in input()
always return a str
object. You need to cast it to int
.
factorial_number = int(input("give an integer that you want to factor: "))
print(factorial(factorial_number))

Fukiyel
- 1,166
- 7
- 19
0
You can handle is as soon as you get the input, see below example:
if factorial_number.isdigit():
factorial_number = int(factorial_number)
else:
print("It's only for integers")

Amit Nanaware
- 3,203
- 1
- 6
- 19
-
2Won't work with negative numbers which are valid integers. Wrap in a try/except instead; "easier to ask for forgiveness than permission" – roganjosh Mar 08 '19 at 13:28
-
@roganjosh although true in general, it would be fine in this case because factorials are only defined for non-negative integers – meowgoesthedog Mar 08 '19 at 13:30