The most common answer is:
MAX = 1000
num1 = 0
num2 = 1
print(1)
while (num1 + num2 < MAX):
ans = num1 + num2
num1 = num2
num2 = ans
print(ans)
This code aims to print the Fibonacci sequence up to a maximum value of 1000. However, it seems to miss printing the initial value of the sequence, which is 0.
Here’s the corrected and slightly optimized version of your code to include the entire sequence from the start:
MAX = 1000
num1 = 0
num2 = 1
print(num1) # Print the initial value of the sequence
print(num2) # Print the second value of the sequence
while (num1 + num2 < MAX):
ans = num1 + num2
print(ans)
num1, num2 = num2, ans # Update num1 and num2 for the next iteration
This code will correctly print the Fibonacci sequence starting from 0, continuing until the last number that is less than 1000. The use of num1, num2 = num2, ans
is a more Pythonic way to update the values of num1
and num2
for the next iteration.
Leave a comment