In Python, arithmetic operators are fundamental components for performing mathematical operations on numeric values. These operators enable you to carry out addition, subtraction, multiplication, division, and other basic arithmetic computations within your code. Python supports the following arithmetic operators:
Understanding and effectively using these arithmetic operators is essential for performing numerical calculations and building mathematical logic in Python programs. They form the basis for a wide range of computations and are integral to various aspects of programming, from simple calculations to complex algorithms.
the addition and subtraction operators are considered to be two of the binary operator.
The addition operator is the +
(plus) sign, which is fully in line with mathematical standards.
Example:
print(-10 + 10) print(-4. + 8) print(+2) # output >> 0 # integer type >> 4. # float type >> 2 # positive integer type
The subtraction operator is obviously the -
(minus) sign, although you should note that this operator also has another meaning - it can change the sign of a number.
Example:
print(-2) print(10 -10) print(-4. -5) # output >> -2 # negative integer type >> 0 # integer type >> -9. # negative float type
An *
(asterisk) sign is a multiplication operator.
Example:
print(2 * 4) print(2 * 3.) print(2. * 3) print(2. * 3.) print((-2) * (3.)) # output >> 8 # positive integer type >> 6.0 # positive float type >> 6.0 # positive float type >> 6.0 # positive float type >> -6.0 # negative float type
Floor division //
returns the largest integer that is less than or equal to the result of the division. It essentially rounds down the result to the nearest whole number.
For example:
print(7/3) # Output: >> 2.333333333333333... print(7//3) # Output: >> 2
In this case, 7 divided by 3 results in 2, and the decimal part (0.3333...) is discarded.
Another example: Let's find out how many hours we have in 325 minutes.
print(325 // 60) # Output: >> 5 # then we have 5 hours, 325 = 5*60 + 25 and the remainder is 25 minutes
i will let you guess the result of:
print(5 // 6) # Output: >> ?
The modulo operation is denoted by the percent sign %
. Given two numbers, a
(the dividend) and b
(the divisor), the result of a % b
is the remainder when a
is divided by b
. The formula can be expressed as:
Examples:
Positives numbers
print(7 % 3) print(15 % 4) # Output: >> 1 >> 3
Negatives numbers
print(-7 % 3) print(7 % -3) # Output: >> 2 >> -2
i will let you guess the result of:
print(-7 % -3) # Output: >> ?