script_11.py - Fibonacci Sequence Generator
Code
#!/usr/bin/env python3
"""Fibonacci sequence generator"""
n = int(input("How many Fibonacci numbers? "))
a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a + b
Explanation
Line 4: n = int(input("How many Fibonacci numbers? "))
- n stores how many numbers to generate
Line 6: a, b = 0, 1
- Tuple unpacking (multiple assignment in one line)
- a gets value 0, b gets value 1
- Both variables assigned simultaneously
- Comma creates a tuple: (0, 1)
- Variables get corresponding tuple elements
Line 8: for _ in range(n):
- _ is the loop variable (underscore)
- Convention: use _ when you don't need the loop value
- Just need to repeat n times, don't care about counter
- _ is still a valid variable, just conventionally "ignored"
Line 10: a, b = b, a + b
- Simultaneous assignment (tuple unpacking)
- Right side evaluated first as tuple: (b, a+b)
- Then both variables updated at once
- Example: if a=0,b=1: (b, a+b) = (1, 0+1) = (1, 1), so a=1,b=1
- Then: if a=1,b=1: (b, a+b) = (1, 1+1) = (1, 2), so a=1,b=2
- Critical: both use old values for calculation, then both updated
- Fibonacci pattern: each number is sum of previous two