Adding numbers in Python is relatively straightforward, but it’s a core function in any Python script and can be used in a multitude of ways. This tutorial’ll cover some basic methods of adding numbers using Python.
Adding Two Numbers
The simplest way to add numbers in Python is by using the + operator. This operator adds two numbers.
1 2 3 |
a = 5 b = 7 sum = a + b |
Adding Multiple Numbers
This is as simple as adding two numbers. Just put + operator between each number you want to add.
1 2 3 4 |
a = 1 b = 2 c = 3 sum = a + b + c |
Using Functions to Add Numbers
Python comes with a built-in function sum() for adding numbers. This function takes an iterable and returns the sum of all values.
1 2 |
x = [1, 2, 3, 4, 5] total = sum(x) |
Built-in Python Function For Adding Numbers
You’ll find a comprehensive description of Python’s built-in functions in the Python Documentation.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 |
a = 5 b = 7 sum = a + b a = 1 b = 2 c = 3 sum = a + b + c x = [1, 2, 3, 4, 5] total = sum(x) |
Conclusion
By following the steps in this tutorial, you’ll be able to add numbers in Python either by using the plus operator or the built-in sum function. Remember, practice is the key, so keep trying out different ways of adding numbers using Python. Happy coding!