Fibonacci Series Up to N
Print a number of Fibonacci terms with Python. Students handle short sequences first, update two previous terms, and separate a term count from a value limit.
1# Take n2n = int(input("Enter number of terms: "))34# Generate Fibonacci5if n <= 0:6 print("Invalid input")7elif n == 1:8 print("0")9elif n == 2:10 print("0 1")11else:12 a, b = 0, 113 print(a, b, end=" ")14 for i in range(2, n):15 c = a + b16 print(c, end=" ")17 a, b = b, c18 print()
Output
Enter number of terms: 8 0 1 1 2 3 5 8 13
In this one
- Handle short sequences
- Update a previous-term pair
- Distinguish count from limit
How it works
- 1
Handle nonpositive, one-term, and two-term cases.
- 2
Otherwise print zero and one, then calculate each new sum.
- 3
Shift a and b after printing c.
Edge cases
What does n = 1 print?
What does n = 1 print?
Only zero.
What does n = 0 print?
What does n = 0 print?
Invalid input; this version requires a positive term count.
What's going on
Here n is the number of terms, not the largest allowed term. The sequence begins zero, one; later terms add the previous two.
Short-input branches cover invalid counts, one term, and two terms. Otherwise the code prints the first pair, then calculates n - 2 more terms. a, b = b, c shifts the previous values together, after c has been computed.
What does n = 1 print? Only zero.
What does n = 0 print? Invalid input; this version requires a positive term count.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the next term after 0, 1, 1?
Pick an answer to check it.
Question 2
What does n = 1 print?
Pick an answer to check it.
Questions people ask
What does n = 1 print?
Only zero.
What does n = 0 print?
Invalid input; this version requires a positive term count.
What is the next term after 0, 1, 1?
2.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum