Python is the best programming language that is easily learned by anyone. Doing arithmetic operations in Python is a very basic skill every coder should know. You can perform calculations like addition, subtraction, multiplication, division, etc. In this tutorial, you will know how to perform arithmetic operations in Python.
Arithmetic operations in Python
Addition
Addition is the process of combining two or more numbers to obtain their total. In Python, the addition operator is represented by the “+” sign. For example, to add two numbers, say 5 and 3, you can use the following code.
num1 = 5
num2 = 3
result = num1 + num2
print(result) # Output: 8
Subtraction
Subtraction involves finding the difference between two numbers. In Python, the subtraction operator is represented by the “-” sign. Below is an example of the subtraction of two numbers.
num1 = 10
num2 = 6
result = num1 - num2
print(result) # Output: 4
Multiplication
Multiplication is the process of repeated addition. In Python, the multiplication operator is denoted by the “*” sign. Here’s an example.
num1 = 4
num2 = 3
result = num1 * num2
print(result) # Output: 12
Division
Division is the process of distributing or partitioning a number into equal parts. In Python, the division operator is represented by the “/” sign. However, it’s worth noting that in Python 2. x, the division between two integers returns an integer, whereas in Python 3. x, it returns a float. Here’s an example:
num1 = 10
num2 = 2
result = num1 / num2
print(result) # Output: 5.0 in Python 2.x, 5.0 in Python 3.x
Modulo
Modulo, or remainder, is the operation that returns the remainder of a division. In Python, the modulo operator is represented by the “%” sign. Below is an example of it.
num1 = 10
num2 = 3
result = num1 % num2
print(result) # Output: 1
Exponentiation
Exponentiation involves raising a base number to the power of an exponent. In Python, the exponentiation operator is denoted by the “**” sign. Here’s an example:
base = 2
exponent = 3
result = base ** exponent
print(result) # Output: 8
Conclusion
Python allows you to perform mathematical operations. The above are the basic arithmetic operations you can do in python. One should note that you should always remember the operator precedence when performing complex calculations. You can use the parentheses to control the order the operations will be calculated.
Leave a Reply