0

I am learning python 3 and now Iam trying to implement factorial function I wrote:

fact = 1
a = input('Enter number for factorial operation: ')

for  b in range ( 1, a+1, 1 ):
    fact = fact * b

print ("Sum is ", fact)

it says:

 for  b in range ( 1, a+1, 1 ):
TypeError: Can't convert 'int' object to str implicitly
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
s900n
  • 3,115
  • 5
  • 27
  • 35

1 Answers1

3

This is happening because input returns you a str, not an int, which is what you're after. You can fix this by casting the str into an int as follows:

a = int(input('Enter number for factorial operation: '))

Take a look at this:

In [68]: a = input('Enter number for factorial operation: ')
Enter number for factorial operation: 5

In [69]: a
Out[69]: '5'

In [70]: type(a)
Out[70]: str

In [71]: isinstance(a, str)
Out[71]: True

In [72]: isinstance(a, int)
Out[72]: False

In [73]: a = int(input('Enter number for factorial operation: '))
Enter number for factorial operation: 5

In [74]: a
Out[74]: 5

In [75]: type(a)
Out[75]: int

In [76]: isinstance(a, str)
Out[76]: False

In [77]: isinstance(a, int)
Out[77]: True
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241