Python Operators

Python Operators

kishore V

Python Operators

In Python, operators are symbols that enable you to perform different kinds of operations on data, such as calculations, comparisons, and logical evaluations. They work on values, variables, or a combination of both to produce a result.

The addition operator (+) is one of the most commonly used operators. It allows you to combine numerical values efficiently.

Example: Adding Two Numbers

Try it Yourself

Here, the + operator adds two integer values and stores the outcome in the variable result.

Example: Adding Variables and Values

The addition operator can also be applied when working with variables, making calculations more flexible and dynamic.

Try it Yourself

Explanation:

base_value and increment store numeric data.
total_one adds two values.
total_two uses a variable and a constant.
total_three adds two variables together.
This method improves code clarity and allows values to be reused across multiple calculations.

Categories of Python Operators

Python classifies operators into several groups based on their functionality:

  • Arithmetic Operators – Perform mathematical calculations (e.g., +, -, *, /)
  • Assignment Operators – Assign values to variables (e.g., =, +=, -=)
  • Comparison Operators – Compare two values (e.g., ==, !=, >, <)
  • Logical Operators – Combine conditional statements (e.g., and, or, not)
  • Identity Operators – Check if two variables reference the same object (e.g., is, is not)
  • Membership Operators – Test for presence in a sequence (e.g., in, not in)
  • Bitwise Operators – Operate at the binary level (e.g., &, |, ^)

Arithmetic Operators in Python

Arithmetic operators in Python are used with numerical data types to carry out basic and advanced mathematical calculations. These operators allow programs to perform operations such as addition, subtraction, multiplication, and different types of division.

Types of Arithmetic Operators

OperatorOperation NameDescription
+AdditionAdds two numbers
-SubtractionSubtracts one value from another
*MultiplicationMultiplies values
/DivisionDivides and returns a decimal value
%ModulusReturns the remainder
**ExponentiationRaises a number to a power
//Floor DivisionReturns the quotient without decimals

Example: Using Arithmetic Operators

Try it Yourself

Explanation:

The program applies different arithmetic operators to the same set of numbers.
Each print() statement displays the result of a specific operation.
Division using / produces a decimal value, even when the numbers divide evenly.

Division Operators in Python

Python supports two types of division, each serving a different purpose.

1. Standard Division (/)

Always returns a floating-point value. Useful when precision is required.

Try it Yourself

2. Floor Division (//)

Returns the largest integer less than or equal to the result. Decimal values are discarded by rounding downward.

Try it Yourself

Key Difference:

/ keeps the decimal part.
// removes the decimal part by rounding down.
This distinction is especially important when working with loops, indexing, or calculations where whole numbers are required.

Assignment Operators in Python

Assignment operators in Python are used to store values in variables. In addition to simple assignment, Python provides compound operators that perform an operation and assign the result back to the same variable in a single step. This helps make code shorter and more readable.

Types of Assignment Operators

OperatorPurposeEquivalent Expression
=Assign valuea = 10
+=Add and assigna = a + 5
-=Subtract and assigna = a - 5
*=Multiply and assigna = a * 5
/=Divide and assigna = a / 5
%=Modulus and assigna = a % 5
//=Floor divide and assigna = a // 5
**=Power and assigna = a ** 5
&=Bitwise AND and assigna = a & 5
|=Bitwise OR and assigna = a | 5
^=Bitwise XOR and assigna = a ^ 5
>>=Right shift and assigna = a >> 2
<<=Left shift and assigna = a << 2

Example: Using Assignment Operators

Try it Yourself

Explanation:

Each operator updates the same variable.
The operation is performed first, and the result is reassigned.
This approach reduces repetitive code.

The Walrus Operator (:=)

Python 3.8 introduced the walrus operator, which allows you to assign a value to a variable while using it within an expression. This is especially helpful in conditions and loops where a value would otherwise be calculated twice.

Example: Without the Walrus Operator

Try it Yourself

Example: With the Walrus Operator

Try it Yourself

Why use the walrus operator?

  • Avoids repeated calculations
  • Makes code more concise
  • Improves readability when used carefully

Assignment operators are widely used in loops, counters, and mathematical updates, making them a core concept in Python programming.

Comparison Operators in Python

Comparison operators in Python are used to evaluate the relationship between two values. These operators compare operands and always return a Boolean result—either True or False. They are commonly used in decision-making statements such as if, while, and conditional expressions.

Types of Comparison Operators

OperatorDescriptionUsage Example
==Checks if two values are equala == b
!=Checks if values are differenta != b
>Checks if left value is greatera > b
<Checks if left value is smallera < b
>=Checks if left value is greater than or equala >= b
<=Checks if left value is less than or equala <= b

Example: Using Comparison Operators

Try it Yourself

Explanation:

Each comparison checks a condition between two values.
The result of every comparison is either True or False.
These Boolean results can be directly used in conditional logic.

Chaining Comparison Operators

Python supports chained comparisons, allowing multiple conditions to be evaluated in a clean and readable way without repeating variables.

Example: Chained Comparison

Try it Yourself

This single line checks whether value lies between 3 and 15.

Equivalent Logical Expression

Try it Yourself

Why use chained comparisons?

  • More readable and concise
  • Reduces repetition
  • Commonly used in range validations

Comparison operators play a vital role in controlling program flow and making decisions based on conditions.

Logical Operators in Python

Logical operators in Python are used to combine multiple conditions and evaluate them as a single Boolean expression. They are most commonly applied in decision-making statements such as if, elif, and while.

Types of Logical Operators

OperatorMeaningExample Usage
andTrue when all conditions are truea > 2 and a < 8
orTrue when at least one condition is truea < 3 or a > 10
notReverses the Boolean resultnot(a == 5)

Example: Using and Operator

Check whether a number falls within a specific range.

Try it Yourself

Explanation:

Both conditions must be true. If either condition fails, the result becomes False.

Example: Using or Operator

Check whether a number is outside a given range.

Try it Yourself

Explanation:

If at least one condition is true, the result is True.

Example: Using not Operator

Invert the outcome of a logical expression.

Try it Yourself

Explanation:

The expression inside parentheses is evaluated first. The not operator flips the Boolean value.
Logical operators are essential for building complex conditions and controlling the flow of Python programs.

Python Identity Operators

Identity operators in Python are used to determine whether two variables reference the same object in memory, rather than just containing equal values. This distinction is important when working with mutable objects like lists, dictionaries, and custom objects.

Types of Identity Operators

OperatorDescriptionExample
isReturns True if both variables refer to the same objecta is b
is notReturns True if variables refer to different objectsa is not b

Example: Using the is Operator

Try it Yourself

Explanation:

list_one and list_three point to the same memory location, so is returns True.
list_two has identical content but is a different object, so is returns False.
The == operator checks only the values, not memory identity.

Example: Using the is not Operator

Try it Yourself

Explanation:

Even though both lists contain the same elements, they are stored separately in memory. Therefore, is not returns True.

Difference Between is and ==

OperatorWhat it Checks
isWhether both variables reference the same object in memory
==Whether the values of the variables are equal

Example: Value vs Identity Comparison

Try it Yourself

Key Takeaway:

  • Use == to compare values
  • Use is to compare object identity

Identity operators are especially useful when checking against singletons like None or when debugging object references.

Membership Operators in Python

Membership operators in Python are used to verify whether a particular value exists within a collection or sequence. These sequences can include lists, tuples, sets, dictionaries, and even strings. The result of a membership check is always a Boolean value: True or False.

Types of Membership Operators

OperatorMeaningExample
inReturns True if the value exists in the sequenceitem in collection
not inReturns True if the value does not exist in the sequenceitem not in collection

Example: Checking Membership in a List

Try it Yourself

Explanation:

The expression checks whether "pencil" exists inside the list. Since it is present, the result is True.

Example: Checking Non-Membership in a List

Try it Yourself

Explanation:

The operator verifies that "marker" is not part of the list. The result is True because the value is absent.

Membership Operators with Strings

Membership operators can also be used to search for characters or substrings within a string.

Try it Yourself

Explanation:

Python string comparisons are case-sensitive, so "python" is not the same as "Python". The in operator checks for exact character or substring matches.
Membership operators are commonly used for validation, searching, and filtering data in Python programs.

Bitwise Operators in Python

Bitwise operators in Python work directly on the binary (bit-level) representation of integers. Instead of treating numbers as whole values, these operators manipulate individual bits, making them useful in low-level programming, performance optimization, and certain algorithmic tasks.

Types of Bitwise Operators

OperatorNameFunction
&ANDSets a bit to 1 only if both corresponding bits are 1
|ORSets a bit to 1 if the bits are different
^XORSets a bit to 1 if the bits are different
~NOTFlips all bits (bitwise inversion)
<<Left ShiftShifts bits left, adding zeros on the right
>>Right ShiftShifts bits right, preserving the sign bit

Example: Bitwise AND (&)

Try it Yourself

Explanation:

Only the bits that are 1 in both numbers remain 1. Binary result: 0000. Decimal result: 0.

Example: Bitwise OR (|)

Try it Yourself

Explanation:

Bits are set to 1 if either value has a 1. Binary result: 1110. Decimal result: 14.

Example: Bitwise XOR (^)

Try it Yourself

Explanation:

Bits are set to 1 only when they differ. Binary result: 1110. Decimal result: 14.

Example: Bitwise NOT (~)

Try it Yourself

Explanation:

The NOT operator flips all bits. The result becomes -6 due to two’s complement representation.

Example: Bit Shifting

Try it Yourself

Explanation:

Left shift multiplies the number by powers of 2.
Right shift divides the number by powers of 2.
Bitwise operators are powerful tools when working with binary data, flags, and optimized computations.

Operator Precedence in Python

Operator precedence determines the sequence in which different operators in an expression are evaluated. When multiple operators appear in a single statement, Python follows a well-defined priority order to decide which operation is performed first. Understanding precedence helps prevent logical errors and ensures expressions behave as expected.

Parentheses Have the Highest Priority

Expressions enclosed in parentheses () are always evaluated before any other operations.

Try it Yourself

Explanation:

Each parenthesized expression is calculated first. The final result is based on those evaluated values.

Multiplication Before Addition

When parentheses are not used, Python follows its built-in precedence rules. For example, multiplication has higher priority than addition.

Try it Yourself

Explanation:

The multiplication 4 * 5 is evaluated first. The result is then added to 50.

Operator Precedence Order (Highest to Lowest)

OperatorDescription
()Parentheses
**Exponentiation
+x, -x, ~xUnary plus, unary minus, bitwise NOT
*, /, //, %Multiplication, division, floor division, modulus
+, -Addition and subtraction
<<, >>Bitwise shifts
&Bitwise AND
^Bitwise XOR
==, !=, >, >=, <, <=, is, is not, in, not inComparison, identity, membership
notLogical NOT
andLogical AND
orLogical OR

Left-to-Right Evaluation

When operators have the same precedence, Python evaluates the expression from left to right.

Try it Yourself

Explanation:

Addition and subtraction share the same precedence. The expression is evaluated sequentially from left to right.

Key Tip

To improve readability and avoid confusion:

  • Use parentheses when writing complex expressions
  • Do not rely only on operator precedence

This completes the rewritten Python Operators section with original explanations and examples. If you want, I can now combine all sections into

Our website uses cookies to enhance your experience. Learn More
Accept !