How to subtract variables in Python?
To subtract variables in Python, use the - operator. It's possible to subtract two or more variables from each other.
subtract integers
# subtract variables - integers
variable1 = 5
variable2 = 3
variable3 = 1
result = variable1 - variable2 - variable3
print(result)
The variable2 and variable3 are subtracted from variable1 and the result is returned.
1
subtract float values
If the variables contain float values instead of integers, the - operators works in the same way. However, the result is returned as float value.
# subtract variables - float values
variable1 = 5.5
variable2 = 3.5
variable3 = 1.0
result = variable1 - variable2 - variable3
print(result)
The variables are subtracted and the result is returned as float value.
1.0
numbers as strings
If the variables contain numbers in string format, a TypeError exception is raised.
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Use the int() function, to convert the strings to integers first.
# subtract variables - numbers as strings
variable1 = "5"
variable2 = "3"
variable3 = "1"
# variables are converted from string to integer
result = int(variable1) - int(variable2) - int(variable3)
print(result)
The variables are first converted from string to integer. Then the values are subtracted and finally the result is returned.
1
subtract using the -= operator
The -= allows it to write the equation in a shorter way.
# subtract variables - using -= operator
variable1 = 5
variable2 = 3
variable3 = 1
# subtract variable2 from variable1
variable1 -= variable2
# subtract variable3 from variable1
variable1 -= variable3
print(variable1)
Using the -= operator, first, the variable2 is subtracted from variable1. Then variable3 is subtracted from variable1. Finally the result is printed.
1