Variable Assignment in Python

Equal sign ( = ) is the assignment operator. The equal sign ( = ) is the main Python assignment operator

anInt = -12
String = 'cart'
aFloat = -3.1415 * (5.0 ** 2)
anotherString = 'shop' + 'ping'
aList = [ 3.14e10, '2nd elmt of a list', 8.82-4.371j ]

Be aware now that assignment does not explicitly assign a value to a variable, although it may appear that way from your experience with other programming languages. In Python, objects are referenced, so on assignment, a reference (not a value) to an object is what is being assigned, whether the object was just created or was a pre-existing object.
Also, if you familiar with C, you are aware that assignments are treated as expressions. This is not the case for Python, where assignments do not have inherent values. Statements such as the following are invalid in Python:

>>> x = 1
>>> y = (x = x+1)
SyntaxError: invalid syntax

Beginning in Python 2.0, the equals sign can be combined with an arithmetic operation and the resulting value reassigned to the existing variable. Known as augmented assignment, statements such as:

x = x + 1

can now be written as :

x += 1

Python does not support pre-/post-increment nor pre-/post-decrement operators such as x++ or –x.


You may also like...