Fall 2024 - P3
3.3 Mathematical Expressions; Fibonacci Sequence
Student led teaching on Mathematical Expressions. Learn how mathematical expressions involve using arithmetic operators (like addition, subtraction, multiplication, and division) to perform calculations
Fibonacci Sequence Function (Python)
def fibonacci(n):
# Handle the base cases. These are also terms that have to be followed by the code.
if n <= 0:
return "Input should be a positive integer."
elif n == 1:
return 0
elif n == 2:
return 1
# Start with the first two Fibonacci numbers
fib_1, fib_2 = 0, 1
# Use an iterative approach to find the nth Fibonacci number. This is the function that models the Fibonacci sequence.
for i in range(3, n+1):
fib_next = fib_1 + fib_2
fib_1, fib_2 = fib_2, fib_next
return fib_2
n = 9
result = fibonacci(n)
print(f"The {n}th Fibonacci number is: {result}")
The 9th Fibonacci number is: 21