Python 3阶乘

时间:2014-09-22 21:19:43

标签: python

我正在学习python 3,现在我试图实现我写的阶乘函数:

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

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

print ("Sum is ", fact)

它说:

 for  b in range ( 1, a+1, 1 ):
TypeError: Can't convert 'int' object to str implicitly

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为input会向您返回str,而不是int,这就是您所追求的。您可以通过将str转换为int来解决此问题,如下所示:

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

看看这个:

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