Basic Operators
Operators are symbols in a programming language that perform operations on values. In Python, there are several operators available for different purposes. Let's explore some of the basic operators and understand their rules and usage.
Exponentiation
The ** (double asterisk) operator is used for exponentiation. It raises the left operand to the power of the right operand. Take a look at the following example:
print(2 ** 3)
Here, 2 raised to the power of 3 is equal to 8. It's important to note that if both operands of the exponentiation operator are integers, the result will also be an integer. However, if at least one operand is a float, the result will be a float as well.
Multiplication
The * (asterisk) operator is used for multiplication. It multiplies the values of the operands. Let's see an example:
print(2 * 3)
In this case, multiplying 2 by 3 gives us the result 6. Similar to exponentiation, if any of the operands is a float, the result will be a float.
Division
The / (slash) operator is used for division. It divides the value in front of the slash (dividend) by the value behind the slash (divisor). Let's take a look:
print(6 / 3)
Here, 6 divided by 3 gives us the result 2.0. It's important to note that the result of division is always a float, even if the dividend and divisor are integers.
Integer Division (Floor Division)
The // (double slash) operator is used for integer division. It performs division and rounds down the result to the nearest whole number. Let's see an example:
print(7 // 3)
In this case, 7 divided by 3 gives us the result 2. The fractional part is discarded, and only the integer part is returned. Integer division follows the same rules as division regarding the result type.
Remainder (Modulo)
The % (percent) operator is used to calculate the remainder of a division operation. It returns the value left over after dividing the left operand by the right operand. Let's see an example:
print(7 % 3)
In this case, when 7 is divided by 3, the quotient is 2, and the remainder is 1. The modulo operator gives us the remainder, which is.
Addition
The + (plus) operator is used for addition. It adds the values of the operands. Let's see an example:
print(2 + 3)
Subtraction
The - (minus) operator is used for subtraction. It subtracts the value on the right side of the operator from the value on the left side. Let's take a look:
print(5 - 2)