Generating Fibonacci series in Python
Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.
Approach
- Take input from the user for the number of terms in the series.
- Initialize two variables a and b with the first two terms of the series, i.e., 0 and 1.
- Then, using a while loop, generate the series and print it.
Code
```python
# taking input from user
nterms = int(input("How many terms? "))
# initialization
a, b = 0, 1
count = 0
# check if the number of terms is valid
if nterms <=>=>
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(a)
else:
print("Fibonacci sequence:")
while count < />
print(a)
nth = a + b
# update values
a = b
b = nth
count += 1
```
Explanation
In the above code, we first take input from the user for the number of terms in the series. Then we initialize two variables a and b with the first two terms of the series, i.e., 0 and 1. We also initialize a variable count to keep track of the number of terms generated so far.
Next, we check if the number of terms is valid or not. If nterms is less than or equal to 0, we print an error message and exit the program. If nterms is 1, we print the first term of the series and exit the program.
If nterms is greater than 1, then we print the first two terms of the series, and using a while loop, we generate the remaining terms of the series and print them. In each iteration of the while loop, we first print the current value of a, which is the nth term of the series. Then we calculate the next term of the series, which is the sum of the current term a and the previous term b. Finally, we update the values of a and b to generate the next term of the series.
Once all the terms in the series have been generated and printed, the program terminates.