Arithmetic operators in python

Arithmetic operators in python: addition, subtraction, division, multiplication, modulus, exponentiation

Introduction to Arithmetic Operators in Python

Arithmetic operators are used to perform some common mathematical operations or calculations such as addition(+), subtraction(-), multiplication(*), division(/), and more.

Basic Addition (+):

Adds two operands.

Python

Basic Subtraction (-):

Subtracts the right operand from the left.

Python

Basic Multiplication (*):

Multiplies two operands.

Python

Basic Division (/):

Divides the left operand by the right. The result is always a floating-point number.

Python

Basic Floor Division(//):

Performs integer division, discarding the remainder.

Python

Basic Modulus(%):

Returns the remainder of dividing the left operand by the right.

Python

Basic Exponentiation(**):

Raises the left operand to the power of the right operand.

Python

Understanding Operator Precedence in Python

When you combine multiple arithmetic operations in a single expression, Python needs to decide which operation to perform first. This decision is governed by a set of rules known as operator precedence. If you're familiar with the mathematical order of operations (PEMDAS/BODMAS), then this concept will feel very natural.

In Python, arithmetic operators follow a specific hierarchy from highest to lowest precedence, which determines the order in which expressions are evaluated.

Let’s break it down:

Exponentiation (**): Highest Precedence

The exponentiation operator has the highest precedence among all arithmetic operators. This means Python evaluates power operations first, even if they appear after other operations in the expression.

Example:

Python

Even though + appears before **, exponentiation is evaluated first.

Multiplication (*), Division (/), Floor Division (//), and Modulus (%): Medium Precedence

These operators come next in the hierarchy. If an expression contains several of these at the same level, they are evaluated from left to right (known as left-associativity).

Example:

Python

Notice that multiplication and division are evaluated before addition, and in the order they appear from left to right.

Addition (+) and Subtraction (-): Lowest Precedence

These are the most basic arithmetic operations and are evaluated last unless overridden by parentheses.

Example:

Python

Although addition appears first in the expression, multiplication takes precedence.

Use Parentheses to Control the Order

When in doubt, or when you want to make your intentions crystal clear, use parentheses () to override the default precedence and ensure operations are evaluated in the desired order.

Example:

Python

Full Operator Precedence Summary (Highest to Lowest):

Precedence Level

Operators

Description

1 (Highest)

**

Exponentiation

2

*, /, //, %

Multiplication, Division, Floor Division, Modulus

3 (Lowest)

+, -

Addition, Subtraction

Ads