Custom Search

PYTHON: Assignment Operators

Assignment operators are used to assign values to variables.

= x = 5 x = 5 simply assigns the value making x become 5
+= x += 3 x = x + 3 This increases whatever value x was before by 3
-= x -= 3 x = x - 3 This decreases whatever value x was before by 3
*= x *= 3 x = x * 3 This multiplies what ever value x was before by a factor of 3
/= x /= 3 x = x / 3 This divides what ever value x was before by a factor of 3
%= x %= 3 x = x % 3

This assigns a new modulus to x

x = 5 (x is a number 5 - to base 10 like we are used to!)

x%=3 (here we assign the decimal number 5 to base 3)

print(x)

The outcome is the number 2

//= x //= 3 x = x // 3

This 'floor divides' x by three - will divide by three and report the integer value - no remainder

For example:

x = 7

x=x//3

print(x)

will return 2 as 7 ÷ 3 = 2 remainder 1 or 2.333

**= x **= 3 x = x ** 3

The raises a variable's value to the power of whatever number is after the '**' - in other words exponentiation of the variable's value.

For example:

x = 2

x=x**3

print(x)

will return 8 as 23 = 2 x 2 x 2 = 8

&= x &= 3 x = x & 3 & is the AND Bitwise operator
|= x |= 3 x = x | 3 | is the OR Bitwise operator
^= x ^= 3 x = x ^ 3 ^ is the XOR Bitwise operator
>>= x >>= 3 x = x >> 3 >> is the fill right shift Bitwise operator
<<= x <<= 3 x = x << 3 << is the Zero fill left shift Bitwise operator