spyder-ide / spyder

Official repository for Spyder - The Scientific Python Development Environment
https://www.spyder-ide.org
MIT License
8.34k stars 1.62k forks source link

is "=" wrong #6096

Closed sanjundong closed 6 years ago

sanjundong commented 6 years ago

Description

What steps will reproduce the problem?

the program is like this:

a,b,c=1,2,3
while c<30:
    print(a,b,c);
    a,b,c=b,c,a+b;

the result is like:

1 2 3
2 3 3
3 3 5
3 5 6
5 6 8
6 8 11
8 11 14
11 14 19
14 19 25

but when i change the program like this

a,b,c=1,2,3
while c<30:
    print(a,b,c);
    a,b=b,c
    c=a+b;

the result is like

1 2 3
2 3 5
3 5 8
5 8 13
8 13 21

so i think something is wrong!

Version and main components

Dependencies

pyflakes >=0.6.0 :  1.5.0 (OK)
pep8 >=0.6       :  1.7.0 (OK)
pygments >=2.0   :  2.2.0 (OK)
qtconsole >=4.2.0:  4.3.0 (OK)
nbconvert >=4.0  :  5.1.1 (OK)
pandas >=0.13.1  :  0.20.1 (OK)
numpy >=1.7      :  1.12.1 (OK)
sphinx >=0.6.6   :  1.5.6 (OK)
rope >=0.9.4     :  0.9.4-1 (OK)
jedi >=0.9.0     :  0.10.2 (OK)
matplotlib >=1.0 :  2.0.2 (OK)
sympy >=0.7.3    :  1.0 (OK)
pylint >=0.25    :  1.6.4 (OK)
csabella commented 6 years ago

This is how Python works. Please see the official documentation at https://docs.python.org/3/reference/simple_stmts.html#assignment-statements, specifically the following line:

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:

x = [0, 1]
i = 0
i, x[i] = 1, 2         # i is updated, then x[i] is updated
print(x)

Stack Overflow may be better suited to explain the details of Python assignment than we are.

CAM-Gerlach commented 6 years ago

For what its worth, if an (unimaginative) interviewer ever asks you the cliched question "How do you swap two variables without a temp variable", you just discovered the (trivial) Python answer.

Also, protip: use triple backticks

code

for code blocks so they show up properly.