-2

i want to swap two numbers in the following way but i don't know why it gives the syntax error

numOne = 10;

numTwo = 20;

numTwo = numOne + numTwo - (numOne = numTwo);

it gives syntax error at = of (numOne = numTwo)

is there any reason and the solution??

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • 1
    Does this answer your question? [Is there a standardized method to swap two variables in Python?](https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python) – Iain Shelvington Oct 09 '21 at 09:53

3 Answers3

3

An assignment statement, e.g. x = y, is not an expression in Python. So while chained assignments are allowed, e.g. a = b = c, embedded assignments using the = operator or not.

That having been said, Python 3.8 introduced the "walrus operator", :=, which allows assignment expressions. So in Python 3.8 and later, you can do:

numTwo = numOne + numTwo - (numOne := numTwo)

to achieve the desired result. You can read about the walrus operator here and, in more detail, here.

But in Python, the normal way to swap two variables a and b is:

a, b = b, a

That's all that's needed.

Also note that none of the semicolons in the posted code are necessary, and would normally not be present.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

Just split the assignment and calculation into separate statements. Python is neither C not C++, assignment operator does not return anything, so most likely you’re trying to perform some mathematical operation on None. Imagine adding int and void in C, that wouldn’t work either, right?

alagner
  • 3,448
  • 1
  • 13
  • 25
0

swapping 2 number is super easy in python:

numOne = 10;

numTwo = 20;

numOne, numTwo = numTwo, numOne
Rish
  • 804
  • 8
  • 15