How to subtract two numbers in Python

Published on Aug. 22, 2023, 12:16 p.m.

To subtract two numbers in Python, you can simply use the - operator. Here is an example code that subtracts two numbers and prints the result:

num1 = 10
num2 = 5
result = num1 - num2
print(result)

This will output 5, which is the result of subtracting num2 from num1.

If you want to subtract two numbers entered by the user, you can use the input() function to prompt the user to enter the two numbers, convert the input to integers using the int() function, and then subtract them. Here is an example code that does this:

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

This will prompt the user to enter the two numbers, subtract num2 from num1, and print the result.

Note that you can also define a function to subtract two numbers. For example:

def subtract(num1, num2):
    return num1 - num2

num1 = 10
num2 = 5
result = subtract(num1, num2)
print(result)

This will output 5, which is the result of subtracting num2 from num1 using the subtract() function.

Tags:

related content