1. 程式人生 > 其它 >Python錯誤:TypeError: unsupported operand type(s) for +: ‘NoneType‘ and ‘NoneType‘

Python錯誤:TypeError: unsupported operand type(s) for +: ‘NoneType‘ and ‘NoneType‘

>>> def fab(n):
		if n == 1 or n == 2:
			sum = 1
		else:
			sum = fab(n - 1) + fab(n - 2)	
>>> fab(10)

報錯:TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘NoneType’

報出這樣的錯誤。
在這裡插入圖片描述
改正以後:

>>> def fab(n):
		if n == 1 or n == 2:
			sum = 1
		else:
			sum = fab(n - 1) +
fab(n - 2) return sum >>> fab(10) 55 >>> fab(20) 6765 >>>

原因:沒有在函式中寫返回語句(return XXX)