Variable assignment in expressions

后端 未结 4 1930
傲寒
傲寒 2021-01-16 13:36

Here is my code to generate values in the fibonnacci sequence below 10,000,000.

  3 fibs = [1,1]
  4 while((x = fibs[-1] + fibs[-2]) <= 10000000):
  5             


        
4条回答
  •  佛祖请我去吃肉
    2021-01-16 14:07

    Basically:

    fibs = [1]
    x = 1
    
    while(x <= 10000000):
      fibs.append(x)
      # It is not possible for "fibs" not to have
      # at least two elements by now
      x = fibs[-1] + fibs[-2]
    

    (It was, in fact, one of the design goals of Python to avoid mixing expressions and assignments like C — that's why there's no x++, x--, which is also a semi-FAQ.)

提交回复
热议问题