我不是很明白我的代码片段在哪里,这看起来很简单,但是编译器向我返回了错误。
choice = input("Enter a number: ")
def fact(num):
if(num == 0):
return 1
return num * fact(num-1)
factorial = fact(choice)
print("The factorial of %d is %d." % (choice, factorial))
该函数运行良好,仅与将返回值设置为变量有关,或者可能与我的print()
语句中的问题有关。我只是在编码一些随机的东西,以帮助我更好地理解python语法。
编辑:错误
Enter a number: 3
Traceback (most recent call last):
File "practice.py", line 10, in <module>
factorial = fact(choice)
File "practice.py", line 8, in fact
return num * fact(num-1)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
答案 0 :(得分:4)
input
返回一个您需要转换为整数的字符串。
choice = int(input("Enter a number: "))
您的示例works in Python 2,因为input
会尝试假设输入值的类型。