Informatics Practices · Ch 3 — Brief Overview of Python
A variable is only useful if you can put a value into it — and change that value later. That is exactly what an assignment operator does: it assigns a value to the variable on its left, or changes the value that variable already holds. The variable always sits on the left of the operator, and the value (or expression) being stored sits on the right.
=The plain = takes whatever is on its right and stores it in the variable named on its left. The right side can be a constant, another variable, or any expression:
>>> num1 = 2
>>> num2 = num1
>>> num2
2
>>> country = 'India'
>>> country
'India'
Notice that num2 = num1 copies the value of num1 into num2 — after the assignment, num2 holds 2. Assignment works for every type of value, strings included.
Programs very often update a variable using its own current value — add something to it, subtract something from it. Python provides shorthand operators that combine an arithmetic operation with assignment in a single step.
Add and assign (+=). It adds the value of the right-side operand to the left-side operand and assigns the result back to the left-side operand. Writing x += y is the same as writing x = x + y:
>>> num1 = 10
>>> num2 = 2
>>> num1 += num2
>>> num1
12
>>> num2
2
``` …
| Operator | Description | Example (Try in Lab) |
|---|---|---|
| = | Assigns value from right side operand to left side operand | >>> num1 = 2>>> num2 = num1>>> num22>>> country = 'India'>>> country'India' |