forked from PLPAfrica/Feb_2024-Python-Hackathon1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
46 lines (36 loc) · 1.43 KB
/
functions.py
File metadata and controls
46 lines (36 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Functions & Fibonacci Sequence
# Question
# Write a Python program to generate the Fibonacci sequence up to a specified term n. The Fibonacci sequence starts with 0 and 1, and each subsequent term is the sum of the two preceding terms.
#We have provided you with in-complete code, from the Knowledge learned from week 1 to week 3 please complete the missing parts to achieve the goal of the question.
def fibonacci(n):
"""
This function generates the Fibonacci sequence up to a specified term n using iteration.
Args:
n: The number of terms in the Fibonacci sequence.
Returns:
A list containing the Fibonacci sequence up to n terms.
"""
if n <= 0:
return fibonacci_sequence
elif n == 1:
fibonacci_sequence.append(0)
else:
fibonacci_sequence.extend([0, 1])
a, b = 0, 1
for _ in range(2, n + 1):
c = a + b
fibonacci_sequence.append(c)
a,b = b, c
return fibonacci_sequence
# Get the number of terms from the user
num_terms = int(input("Enter the number of terms: "))
# Generate the Fibonacci sequence
fibonacci_sequence = []
for i in range(num_terms):
fibonacci_sequence.append(fibonacci(i))
# Print the Fibonacci sequence
print(fibonacci_sequence)
# Your program should:
# Ask the user to input the value of n.
# Create a function that takes n as a parameter and returns a list containing the first n terms of the Fibonacci sequence.
# Print the generated Fibonacci sequence.