How to Subtract in Python

Posted in Python by Dirk - last update: Dec 18, 2023

Subtraction in Python is achieved using the - operator. For instance, result = number1 - number2 subtracts number2 from number1, storing the result in the variable ‘result’.

It is important that when performing arithmetic operations like subtraction that all variables are numerical. When subtracting two variables of different types, Python automatically performs a type conversion to a common type before the operation

Python has the following numerical variable types :

  1. Integers (int): Whole numbers without decimals, e.g., 1, -5, 100.
  2. Floating-point numbers (float): Numbers with decimals, e.g., 3.14, -0.5, 2.0.
  3. Complex numbers (complex): Numbers with real and imaginary parts, e.g., 2 + 3j.

The Basic Syntax

In Python, you can subtract numbers using the subtraction operator (-). Here’s a simple example:


# Subtraction example

a = 5
b = 3
result = a - b

print("Result:", result)

In this example, a and b are variables containing numbers, and result is assigned the value of the subtraction of b from a. The result will be 2 in this case.

You can also perform subtraction with variables, constants, or a combination of both. Just use the - operator between the values you want to subtract.

An example with a variable and a number:

# Subtraction example

a = 5

result = a - 3

print("Result:", result)

Here’s another example, this time with user input:

# Subtraction with user input

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 - num2

print("Result:", result)

In this example, the input function is used to get user input, and float() is used to convert the input to floating-point numbers (in this simple case it is assumed that user only enters integer or floating point values, see below how to handle ValueErrors)

Subtracting Numbers that are stored as Strings

If you get the error TypeError: unsupported operand type(s) for -: 'str' and 'str' you are trying to perform subtraction (-) between two strings. In Python, the - operator is not defined for strings, and you cannot subtract one string from another directly.

To resolve this issue, you need to make sure that you are performing subtraction on numeric values, not strings. If you are getting input from the user, you might want to convert the input to numeric types (e.g., int or float) before performing the subtraction.

Here’s an example of how you can handle user input to avoid this error:

# Subtraction with user input, handling string input

try:
    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    result = num1 - num2
    print("Result:", result)
except ValueError:
    print("Error: Please enter valid numeric values.")

In this example, the float() function is used to convert user input to floating-point numbers, and a try-except block is used to catch any ValueError that might occur if the user enters a non-numeric value. If a ValueError occurs, a message is printed, indicating that valid numeric values should be entered.

How to check if a variable is numerical?

1. Using the ’type’ function

Python type() is a built-in function that returns the type of data stored in a variables:

# Checking the type of variable 

number_as_string = "1"
print(type(number_as_string))# prints: <class 'str'>

number_integer = 1
print(type(number_integer))# prints: <class 'int'>

number_floating = 1.1
print(type(number_floating))# prints: <class 'float'>

number_complex = 1.0 + 1.1j
print(type(number_complex))# prints: <class 'complex'>

2. Using the ’numbers’ function

Here we use the numbers module, this module provides an easy way to test whether an object is a number of some kind without checking for a specific type. This can be useful when you want to check if an object supports common numeric operations without caring about the exact numeric type.


# Importing the numbers module 
from numbers import Number


number_as_string = "1"
print(isinstance(number_as_string, Number)) # prints: False

number_integer = 1
print(type(number_integer)) # prints: True

number_floating = 1.1
print(type(number_floating)) # prints: True

number_complex = 1.0 + 1.1j
print(type(number_complex)) # prints: True

3. Using ’try’ and ’except’ for type conversion:

With try and except you check if your variable is of a specific type. If yes, your code can be executed, if not, you can handle the exception with your code



try:
    float(variable)
    ## if variable is of type float - the code you put below will be executed
    ## ... your code here ...

except (ValueError, TypeError):
    ## the variable is not of type float - handle the error (print error message, do something else)
    ## ... your code here ... 

Summary Each approach has its advantages and considerations. The choice may depend on the specific requirements of your code. The first two methods are more explicit, while the third one relies on the ability to perform a type conversion without raising an exception.

Subtracting integers (int) and floating point numbers (float)

When subtracting two variables of different types, Python automatically performs type conversion to a common type before the operation. Typically, the result will be of the more general type. For example, when subtracting an integer from a float, the result will be a float.

# Subtracting an integer from a float
float_var = 5.0
int_var = 3

result = float_var - int_var

print("Result:", result)

In this example, float_var is a float, and int_var is an integer. The subtraction is performed, and the result is automatically converted to a float. You can also explicitly convert one of the variables to the type of the other if needed.

# Explicit conversion before subtraction
float_var = 5.0
int_var = 3

result = float_var - float(int_var)  # Convert int_var to float before subtraction

print("Result:", result)

In this case, the float(int_var) converts the integer int_var to a float before the subtraction.

Subtract a value from a variable

To subtract a value from a variable and assign the new value to the same variable, you can use the subtraction operator (-) along with the assignment operator (=). Here’s an example:

# Subtract a value from a variable and assign the new value
x = 10
subtract_value = 3

# Subtract and assign
x = x - subtract_value

# Alternatively, you can use the shorthand: x -= subtract_value
# This is equivalent to x = x - subtract_value

# Print the result
print("Updated value of x:", x)

In this example, the value of subtract_value is subtracted from the variable x, and the result is assigned back to the variable x. The final value of x will be 7 in this case.

You can also use the shorthand notation x -= subtract_value, which is equivalent to x = x - subtract_value. This shorthand is a concise way to express the same operation.

Other articles