Arithmetic Operators
Arithmetic Operators in Python
Arithmetic operators in Python are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and more.
Python supports 7 arithmetic operators:
-
Addition (
+) -
Subtraction (
-) -
Multiplication (
*) -
Division (
/) -
Modulus (
%) -
Exponentiation (
**) -
Floor Division (
//)
1. Addition Operator
The + operator adds two numbers.
Output:
2. Subtraction Operator
The - operator subtracts the second number from the first.
Output:
3. Multiplication Operator
The * operator multiplies two numbers.
Output:
4. Division Operator
The / operator divides the first number by the second and returns a floating-point result.
Output:
5. Modulus Operator
The % operator returns the remainder after dividing the first number by the second.
Output:
6. Exponentiation Operator
The ** operator raises the first number to the power of the second.
Output:
7. Floor Division Operator
The // operator divides the first number by the second and returns the integer part of the result.
Output:
Operator Precedence and Associativity
Understanding precedence and associativity is important when evaluating complex arithmetic expressions.
Operator Precedence (Highest to Lowest):
-
**(Exponentiation) -
*,/,//,%(Multiplication, Division, Floor Division, Modulus) -
+,-(Addition, Subtraction)
Example:
Output:
Explanation:
-
In the first line, multiplication is performed before addition.
-
In the second, exponentiation is evaluated first, then multiplication, then addition.
Operator Associativity
Associativity decides how operators of the same precedence are grouped.
-
Most operators (like
+,-,*,/,//,%) have left-to-right associativity. -
Only
**has right-to-left associativity.
Left-to-Right Associativity:
Output:
Explanation:
Evaluated as (20 - 5) + 2
Right-to-Left Associativity:
Output:
Explanation:
-
3 ** 2 ** 1is evaluated as3 ** (2 ** 1)→3 ** 2→9
Comments
Post a Comment