46.9k views
3 votes
CodeHS AP CSP 4.10.5 Fibonacci

** PLEASE ANSWER THIS QUESTION USING PYTHON CODE!!! **
Write a program that prints out the numbers in the Fibonacci sequence up until the max number. You can figure out the next number in the Fibonacci sequence by adding the two previous numbers.
The first number is 1 and the second number is 1. To get the third number we take 1 + 1 = 2. To get the fourth number we take the second number plus the third number (1 + 2 = 3).
Here is a sample run of the program.
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

User Thorsley
by
7.4k points

2 Answers

5 votes

Final answer:

To print out the Fibonacci sequence up until a max number, use a while loop in Python.

Step-by-step explanation:

To print out the numbers in the Fibonacci sequence up until a max number in Python, you can use a while loop. Start by initializing two variables, 'first' and 'second,' to 1. Then, print the value of 'first.' While 'second' is less than or equal to the max number, update 'first' and 'second' to be the previous two numbers in the Fibonacci sequence, and print the value of 'second'.

Here is an example code:

first = 1
second = 1

print(first)

while second <= max_number:
print(second)
temp = second
second = first + second
first = temp

For example, if the max number is 100, the program will print: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.

User Oriberu
by
7.4k points
7 votes

The python code has been used to write the program that prints the Fibonacci sequence

How to write the program

def fibonacci(max_number):

a, b = 1, 1

fibonacci_sequence = [a, b]

while True:

c = a + b

if c > max_number:

break

fibonacci_sequence.append(c)

a, b = b, c

print(*fibonacci_sequence)

# Setting the maximum number

max_num = 10000 # You can change this to any desired maximum number

# Calling the function to print Fibonacci sequence up to the specified maximum number

fibonacci(max_num)

User Nitseg
by
8.2k points