Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion Python/Algorithms/fibonacci_sequence.py
Original file line number Diff line number Diff line change
@@ -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.")