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:

  1. Addition (+)

  2. Subtraction (-)

  3. Multiplication (*)

  4. Division (/)

  5. Modulus (%)

  6. Exponentiation (**)

  7. Floor Division (//)


1. Addition Operator

The + operator adds two numbers.

x = 10 y = 7 result = x + y print(result)

Output:

17

2. Subtraction Operator

The - operator subtracts the second number from the first.

x = 10 y = 7 result = x - y print(result)

Output:

3

3. Multiplication Operator

The * operator multiplies two numbers.

x = 4 y = 6 result = x * y print(result)

Output:

24

4. Division Operator

The / operator divides the first number by the second and returns a floating-point result.

x = 9 y = 2 result = x / y print(result)

Output:

4.5

5. Modulus Operator

The % operator returns the remainder after dividing the first number by the second.

x = 11 y = 4 result = x % y print(result)

Output:

3

6. Exponentiation Operator

The ** operator raises the first number to the power of the second.

base = 3 power = 4 result = base ** power print(result)

Output:

81

7. Floor Division Operator

The // operator divides the first number by the second and returns the integer part of the result.

x = 17 y = 5 result = x // y print(result)

Output:

3

Operator Precedence and Associativity

Understanding precedence and associativity is important when evaluating complex arithmetic expressions.


Operator Precedence (Highest to Lowest):

  1. ** (Exponentiation)

  2. *, /, //, % (Multiplication, Division, Floor Division, Modulus)

  3. +, - (Addition, Subtraction)

Example:

print(8 + 3 * 2) print(6 + 2 * 5 ** 2)

Output:

14 56

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:

print(20 - 5 + 2)

Output:

17

Explanation:
Evaluated as (20 - 5) + 2


Right-to-Left Associativity:

print(3 ** 2 ** 1) print(3 ** (2 ** 1)) print((3 ** 2) ** 1)

Output:

9 9 9

Explanation:

  • 3 ** 2 ** 1 is evaluated as 3 ** (2 ** 1) → 3 ** 2 → 9

Comments

Popular Posts