I'm going over some Python basics and doing exercises on it. One of them is to perform a Fibonacci sequence, which I solved using a while
and a pair of operators +=
. My question is if this code can be made simpler using loops
.
a=1
b=1
print(a)
print(b)
while True:
a+=b
b+=a
if b>1000:
break
print(a)
print(b)
Salida:
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
Thanks in advance :)
As you have it now you are generating the numbers two by two. One way to make it simpler would be to generate them one by one and use tuple assignment:
You can also ask for the number of values and use for loop:
In this case, through input the user is asked to enter the number of values of the sequence that he wishes to generate. The value entered by the user is stored in a variable that in this case I have put "num". int allows you to process this value as an integer. Two variables "a" and "b" are established with an initial value of 0 and 1 respectively, which will allow the calculation of the following values of the sequence. The "for" allows the calculation to be repeated until the value of "num" is reached, which is the number of values of the sequence that the user wants. In this case "a" represents the new calculated value of the sequence and is obtained as the sum of "b" and the previous value of "a", that is, it adds the two previous values of the sequence to obtain the new value.
On the other hand, a more mathematical solution can also be used using python lists:
Also note that the Fibonacci sequence must start at 0, 1.