DEV Community

loading...
Cover image for Assignment Operators in python

Assignment Operators in python

Aswin Barath
Budding Software Engineer | Web Developer | Blogger
Updated on ・1 min read

Assignment operators are used to assigning values to variables.

That is to store values in variables we use = assignment operator.
Alt Text
Output:

3.14
Enter fullscreen mode Exit fullscreen mode

OK, now comes the real fun.
Have ever been tired to use x = x + 5, where we type the variable x twice?
There's actually a shortcut for this called Augmented assignment operators.

Augmented assignment operators can be used as a replacement as follows:

x += 3     --->    x = x + 3    
x -= 3     --->    x = x - 3    
x *= 3     --->    x = x * 3    
x /= 3     --->    x = x / 3    
x %= 3     --->    x = x % 3    
x //= 3    --->    x = x // 3   
x **= 3    --->    x = x ** 3   
x &= 3     --->    x = x & 3    
x |= 3     --->    x = x | 3    
x ^= 3     --->    x = x ^ 3    
x >>= 3    --->    x = x >> 3   
x <<= 3    --->    x = x << 3
Enter fullscreen mode Exit fullscreen mode

Here's the Code and Output

Alt Text

9
6
18
6.0
Enter fullscreen mode Exit fullscreen mode

Alt Text

64
1
0
Enter fullscreen mode Exit fullscreen mode

Alt Text

2
3
Enter fullscreen mode Exit fullscreen mode

Alt Text

0
3
24
Enter fullscreen mode Exit fullscreen mode

Quick Note: The code snippets reuses the same variable to assign with different arithmetic operations / bitwise operations / shift operations.

So, while coding makes sure you practice to use print statements after each operation.

Code along and have fun ;)

Discussion (0)

Forem Open with the Forem app