关于Python斐波那契生成器每轮迭代逻辑的技术咨询
Hey there! I totally get wanting to nail down every detail before moving on—let's walk through this generator step by step so you can see exactly what's happening in each iteration.
First, here's your code again for reference:
def fibonacci_generator() : a , b = 0 , 1 while True : yield a a , b = b , a + b fib = fibonacci_generator() for i in fib : if i > 100 : break else : print( 'Generated:' , i )
Let's start from the very beginning and track every change to a and b:
Initialization
When you run fib = fibonacci_generator(), the function starts executing:
- It sets
a = 0andb = 1in one line (parallel assignment). - It hits the
while Trueloop, then immediately reachesyield a. This pauses the function and "sends" the value0back to the caller—but the function remembers its state (the values ofaandbare still 0 and 1).
Iteration 1 (First print: 0)
- The
forloop grabs the first yielded value (0). Since 0 ≤ 100, it printsGenerated: 0. - Now the generator resumes right after the
yieldstatement. It runsa, b = b, a + b:- The right-hand side calculates first:
bis 1, anda + bis 0 + 1 = 1. - Both values are assigned at the same time:
abecomes 1,bbecomes 1.
- The right-hand side calculates first:
- The generator loops back to
while Trueand pauses atyield aagain, now holdinga = 1.
Iteration 2 (Second print: 1)
- The
forloop gets the next value (1), printsGenerated: 1. - Generator resumes, runs
a, b = b, a + b:- Right-hand side:
bis 1,a + bis 1 + 1 = 2. - Now
a = 1,b = 2.
- Right-hand side:
- Pauses at
yield awitha = 1.
Iteration 3 (Third print: 1)
- Loop grabs
1, prints it. - Generator updates:
atakesb's value (2),btakes1 + 2 = 3. Nowa = 2,b = 3. - Pauses at
yield awitha = 2.
Iteration 4 (Fourth print: 2)
- Loop gets
2, prints it. - Generator updates:
a = 3,b = 2 + 3 = 5. - Pauses at
yield awitha = 3.
Skipping Ahead to the Final Iterations
This pattern continues: each time the generator resumes, it updates a and b using their previous values (thanks to parallel assignment, we don't overwrite a before calculating the new b).
Let's jump to the last few steps before the loop breaks:
- When
a = 89, the loop printsGenerated: 89. - Generator updates:
a = b = 144,b = 89 + 144 = 233. - Next, the
forloop grabs144, which is greater than 100. The loop hitsbreakand stops.
Key Takeaway
The magic here is yield—it lets the function pause and resume, keeping track of its state between calls. The parallel assignment a, b = b, a + b is crucial too: it ensures we use the original values of a and b to calculate the next pair, instead of overwriting a first and messing up the calculation.
内容的提问来源于stack exchange,提问作者combatwombat833

