In this tutorial, we’re going to learn how to write a subtraction function in Python. Python is a powerful language used widely in web development, data analysis, artificial intelligence, and many other spheres. Today we’ll focus on a basic Python function, subtraction, that anyone can use to subtract numbers.
Step 1: Defining the Function
The first step is to define our subtraction function. We do this by using the keyword def, followed by the desired function name, in our case, subtract.
1 2 |
def subtract(a, b): return a-b |
Step 2: Calling the Function
After defining the function, we now need to call or execute it. To call a function in Python, just type the function name followed by parentheses containing any arguments the function requires.
1 |
subtract(10, 5) |
Step 3: Displaying the Output
To display the output, we use the print() function. The print function is a built-in Python function that displays the result to the console.
1 |
print(subtract(10, 5)) |
The Full Code
Here is the full code of what we have done:
1 2 3 |
def subtract(a, b): return a-b print(subtract(10, 5)) |
The Output
The output of your code should look like this:
5
Conclusion
And that’s it! Now you know how to write a subtraction function in Python. This is a fundamental skill and you will use Python functions a lot in your coding journey. Next time when you need to subtract numbers in Python, you can use your own subtract function.
For more learning, you can visit the official Python documentation. Happy learning!