Python
In this tutorial we will learn about Assignment operators in Python.
We use the assignment operator to assign any value or result of an expression to a variable.
In the following Python code we are assigning integer value 10 to the variable x.
x = 10
In the following Python code we are assigning the result of an expression to a variable
y = 10 + 20
Lets say, we have an integer variable x
which is initially set to 10. Then we increase the value by 5 and assign the new value to it.
# declare and set value
x = 10
# increase the value by 5 and re-assign
x = x + 5
Another way of writing the code x = x + 5
is by using the shorthand assignment +=
as shown below.
# declare and set value
x = 10
# increase the value by 5 and re-assign
x += 5
Following is the list of shorthand assignment operators.
Simple assignment | Shorthand assignment |
---|---|
x = x + y | x += y |
x = x - y | x -= y |
x = x * y | x *= y |
x = x / y | x /= y |
x = x % y | x %= y |
x = x ** y | x **= y |
x = x // y | x //= y |
Write Python program to add the value of two variables x and y having value 10 and 20 respectively and print the sum.
# variable
x = 10
y = 20
print("Result:", (x + y))
We can achieve the same result by adding the value of y to x and saving the result in x.
# variable
x = 10
y = 20
# result
x += y
print("Result:", x)
ADVERTISEMENT