Python求第n个斐波那契数报错:'int' object is not subscriptable
'int' object is not subscriptable in Your Fibonacci Python Code Hey there! I’ve run into this exact error a handful of times when tinkering with Fibonacci implementations—let’s break down what’s going on and fix it.
What the Error Actually Means
That error pops up when you try to use square bracket notation ([index]) on an integer. Think about it: you can’t do 5[2] because integers don’t support index access like lists or strings do. In your Fibonacci code, you’ve almost certainly accidentally turned a variable that should be subscriptable (like a list) into an integer, then tried to index it.
Common Culprits in Fibonacci Code
Let’s look at two typical mistakes that trigger this error:
1. Recursive Implementation Mix-Up
You might have written something like this, where you incorrectly try to index the integer result of your recursive call:
def fib(n): if n <= 1: return n fib_total = fib(n-1) + fib(n-2) return fib_total[n] # Oops! fib_total is an int, not a list
The recursive calls return integers, so fib_total becomes a plain number—trying to index it with [n] breaks everything.
2. Iterative Implementation Variable Overwrite
If you’re using an iterative approach, you might have replaced your list variable with an integer mid-loop:
def fib(n): fib_seq = [0, 1] for i in range(2, n+1): fib_seq = fib_seq[i-1] + fib_seq[i-2] # Now fib_seq is an int, not a list! return fib_seq[n]
After the first iteration, fib_seq gets set to a sum (an integer), so any later attempt to index it throws the error.
Corrected Working Code Examples
Here are two solid implementations to fix this:
Recursive Version (Simple)
def fib(n): if n <= 1: return n # No indexing needed—just return the sum of the previous two values return fib(n-1) + fib(n-2)
Iterative Version (More Efficient for Large n)
def fib(n): if n <= 1: return n a, b = 0, 1 for _ in range(2, n+1): a, b = b, a + b # Update values without overwriting a list return b
Quick Debugging Tip
If you want to confirm the issue firsthand, add a print(type(your_variable)) right before the line that throws the error. For example, if the error hits on return fib_seq[n], print print(type(fib_seq))—it’ll show <class 'int'>, which tells you exactly where you turned your subscriptable object into an integer.
内容的提问来源于stack exchange,提问作者Aron Tesfay

