def fibonacci_series(n):
a, b = 0, 1
series = []
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
num_terms = int(input("Enter the number of terms: "))
if num_terms <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci series:")
print(fibonacci_series(num_terms))
#source code --> clcoding.com
Code Explanation:
1. Function Definition: fibonacci_series(n)
The function takes a single parameter, n, which represents the number of terms in the Fibonacci sequence to generate.
Inside the function:
a, b = 0, 1: Initializes the first two numbers of the Fibonacci sequence, where a starts at 0 and b at 1.
series = []: Creates an empty list to store the Fibonacci sequence.
2. Generating Fibonacci Terms
for _ in range(n)::
Iterates n times to generate the sequence.
The loop variable _ is used when the variable itself is not needed.
series.append(a):
Adds the current value of a (the current Fibonacci number) to the series list.
a, b = b, a + b:
Updates a to the value of b (the next Fibonacci number).
Updates b to the sum of a and b (the next-next Fibonacci number).
This update effectively shifts the series forward.
3. Returning the Result
After the loop ends, the complete Fibonacci sequence is stored in series.
The function returns the series list.
Main Program
4. Input from User
num_terms = int(input("Enter the number of terms: ")):
Prompts the user to input the number of terms they want in the Fibonacci sequence.
Converts the input to an integer and stores it in num_terms.
5. Input Validation
if num_terms <= 0::
Checks if the input is less than or equal to 0 (invalid input).
If invalid, prints a message: "Please enter a positive integer.".
else::
If the input is valid (a positive integer), proceeds to generate the Fibonacci sequence.
6. Generating and Printing the Sequence
print("Fibonacci series:"):
Outputs a message indicating that the Fibonacci sequence will follow.
print(fibonacci_series(num_terms)):
Calls the fibonacci_series function with the user-specified number of terms and prints the returned list.
0 Comments:
Post a Comment