diff --git a/Python/Algorithms/fibonacci_sequence.py b/Python/Algorithms/fibonacci_sequence.py index 8d1c8b6..128eddb 100644 --- a/Python/Algorithms/fibonacci_sequence.py +++ b/Python/Algorithms/fibonacci_sequence.py @@ -1 +1,34 @@ - +# Function to generate the Fibonacci sequence up to n terms +def fibonacci_sequence(n): + """Generate Fibonacci sequence up to n terms.""" + if n <= 0: + return [] + elif n == 1: + return [0] + elif n == 2: + return [0, 1] + + # Initialize the sequence with the first two terms + sequence = [0, 1] + + # Generate subsequent terms + for i in range(2, n): + next_term = sequence[i-1] + sequence[i-2] + sequence.append(next_term) + + return sequence + +# Accept input from the user +try: + num_terms = int(input("Enter the number of terms in the Fibonacci sequence: ")) + + if num_terms < 0: + print("Please enter a non-negative integer.") + else: + # Generate and display the Fibonacci sequence + fib_sequence = fibonacci_sequence(num_terms) + print(f"Fibonacci sequence with {num_terms} terms:") + print(fib_sequence) + +except ValueError: + print("Invalid input. Please enter a valid integer.") \ No newline at end of file