2 Replies - 1181 Views - Last Post: 19 April 2012 - 04:23 PM Rate Topic: -----

#1 bennigan88   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-April 12

Multiple Assignments in One Line not working (Fibonacci Sequence)

Posted 19 April 2012 - 12:03 PM

when I run this:
var1,var2,var3=0,0,1
n=int(input("Number of terms: "))
for count in range(n):
    print(var3)
    var1=var2
    var2=var3
    var3=var1+var2



it works fine, but when I turn the 3 assignments in the for loop into one line, like this:
var1,var2,var3=0,0,1
n=int(input("Number of terms: "))
for count in range(n):
    print(var3)
    var1,var2,var3=var2,var3,var1+var2



it outputs this:
Number of terms: 10
1
0
1
1
1
2
2
3
4
5

which is not fine :/ - am I doing something wrong with the syntax, or can i not do this in a for loop?

Is This A Good Question/Topic? 0
  • +

Replies To: Multiple Assignments in One Line not working (Fibonacci Sequence)

#2 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2662
  • View blog
  • Posts: 4,256
  • Joined: 21-June 11

Re: Multiple Assignments in One Line not working (Fibonacci Sequence)

Posted 19 April 2012 - 12:16 PM

When you do var1,var2,var3=var2,var3,var1+var2 the expression var1+var2 refers to the values that var1 and var2 had before this assignment. You can't refer to the new values of var1 and var2 until the next line. (Note that if it didn't work that way, it'd be impossible to swap variables like x,y = y,x - it would just set both variables to y).

So if you want to write it one line, you'll have to write var1, var2, var3 = var2, var3, var2 + var3.
Was This Post Helpful? 1
  • +
  • -

#3 bennigan88   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-April 12

Re: Multiple Assignments in One Line not working (Fibonacci Sequence)

Posted 19 April 2012 - 04:23 PM

makes sense
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1