September 27th, 2003, 03:27 PM

Fibonacci sequence example has be slightly confused
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8

This doesn't entirely make sense to me and I was wonderfing if someone could help explain it. I've just got started in programming and I don't understand how a & b are being assigned completely different variables and how it would make it calculate itself in a continuous loop if it weren't for the while b < 10:
thanks,
NightStalkerX6
September 27th, 2003, 08:34 PM

Hey Night,
First you need to understand that anything after a # up untill the end of the line is a comment, so just forget about them .
The program first assigns the value 0 to a and 1 to b, next it starts a while loop which will continue untill b is not less than 10. Every time the loop runs though it prints the value of b then assignes that value to a and gives b the value of a + b
In theory the loop would keep going, adding a and b and printing the output, anyway i hope that's cleared things up for you
Welcome to Python, have fun!
Mark.
September 30th, 2003, 03:50 PM

wassup NightStalker,
it helps to understand how a and b are assigned different values if you rewrite the code like this:
Code:
a=0
b=1 #separate assignments
while (b < 10):
print b
a = b
b = a + b
i'm not sure if that's exactly what you were asking... if you look through the tutorials for python though, you could easily understand the concept of the while loop
October 29th, 2003, 11:35 AM

oops, i goofed
in a statement such as this:
a,b = b,a+b
...python evaluates all expressions (ie b and a+b) on the right hand side before assigning any values to a or b. the previous example that i gave trying to clarify the assignments was incorrect, so sorry!
it's more like this:
Code:
a=0
b=1 #separate assignments
while(b<10):
A = b
B = a+b #eval before assigning
a=A
b=B #assign after evaluating
sorry yall.
September 13th, 2005, 09:17 PM

This is the simplest way to do it
Variables a, b, c, d
a = 1
b = 0
c = 1
While c < n # number of repetitions
c = c + 1
Print a
d = b
b = a
a = b + d
Loop
September 13th, 2005, 10:46 PM

this is off topic but what is the number called if you divide 2 numbers of the fib sequence together? like 89/55 gets you close to some irrational number. as you move down the fib sequence you get closer and closer to the irrational number.
it has something to do with pentagons too... and other shapes like a dodecahedran.
so you think you can tell heaven from hell
September 13th, 2005, 11:47 PM

It's called the Golden Ratio.
Comments on this post
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!"  Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website."  Nilpo