Published on

Operators in Python - A Comprehensive Guide

Authors

Introduction

Operators in Python are symbols that allow you to perform operations on variables and values. They are essential for manipulating data and controlling program flow. Python provides a wide range of operators categorized into different types.

Python language supports the following types of operators

Arthmetic Operators

Arithmetic operators are used for basic mathematical operations like addition, subtraction, multiplication, division, and more. They are the building blocks of mathematical expressions in Python.

Assume: a=10, b=20

OperatorDescriptionExample
(+) AdditionAdd values on either side of the operatora+b = 30
(-) SubtractionSubtracts right-hand operand from the left-hand operanda-b = -10
(*) MultiplicationMultiplies values on either side of the operatora*b = 200
(/) DivisionDivides left-hand operand by the right operanda/b = 2
(%) ModulusDivides left operands by the right-hand operand and returns the remainderb%a = 0
(**) Exponent/PowerPerforms exponential calculation on operatora**b = 10^20
(//) FloorThe division of operands where the result is the quotient in which the digits after the decimal points are removed9//2 = 4, 9.0 // 2.0 = 4.0, 9.4523//2.4512 = 3.0

Comparison (Relational) Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relation Operators.

Assume: a=10, b=20

|----------|---------------------------------------------------------------------|---------------|

OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes truea==b # false
!=If the values of two operands are not equal, then the condition becomes truea!=b # true
<>If values of two operands are not equal, then the condition becomes truea<>b # true
>If the value of the left operand is greater than the value of the right operand, then the condition becomes truea>b # false
<If the value of the left operand is less than the value of the right operand, then the condition becomes truea < b # true
>=If the value of the left operand is greater than or equal to the value of the right operand, then the condition becomes truea>=b # false
<=If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes truea<=b # true

Assignment Operaators

An assignment operator is the operator used to assign a new value a variable

Assume a=10, b=20

OperatorDescriptionExample
=Assign values from the right-side operand to the left-side operandc=a+b # assigns the value of a+b into c
+=Adds the right operand to the left operand and assigns the result to the left operanda+=b # equivalent to a = a+b
-=Subtracts the right operand from the left operand and assigns the result to the left operanda-=b # equivalent to a = a-b
*=Multiplies the right operand with the left operand and assigns the result to the left operanda*=b # equivalent to a = a*b
/=Divides the left operand by the right operand and assigns the result to the left operanda/=b # equivalent to a = a/b
%=Takes the modulus using two operands and assigns the result to the left operanda%=b # equivalent to a = a%b
**=Performs exponential (power) calculation on operands and assigns the value to the left operanda**=b # equivalent to a = a**b
//=Performs floor division on operands and assigns the value to the left operanda//=b # equivalent to a = a//b

Logical Operators

Logical operators are typically used with Boolean values

Assume a = True, b = False

OperatorDescriptionExample
and (Logical AND)If both operands are true, the condition becomes truea and b # false
or (Logical OR)If any of the two operands are true, the condition becomes truea or b # true
not (Logical NOT)Used to reverse the logical state of its operand!a # false
  • AND truth table (how Logical AND works)

Y (output) : A.B (dot(.) represent multiplication) Above line can also be written as Y = A and B

ABY = A and B
000
010
100
111
  • OR truth table (how Logical OR works)

Y (output) : A+B (plus(+) represent addition) Above line can also be written as Y = A or B

ABY = A + B
000
011
101
112
  • NOT truth table (how Logical NOT works)

Y (output) : !A (! used to give opposite of value; if TRUE then it will false) Means if A = 1, then Y = !A = 0

AY = !A
01
10

Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation

Assume a = 60, b = 13

OperatorDescriptionExample
& (Binary AND)Operators copy a bit to the result if it exists in both operandsa = 0b0011 1100<br>b = 0b0000 1101<br>a & b = 0b0000 1100<br>a & b = 12
&#124; (Binary OR)It copies a bit if it exists in either operanda = 0b0011 1100<br>b = 0b0000 1101<br>a &#124; b = 0b0011 1101<br>a &#124; b = 61
^ (Binary XOR)It copies the bit if it is set in one operand but not botha = 0b0011 1100<br>b = 0b0000 1101<br>a ^ b = 0b0011 0001<br>a ^ b = 49
~ (Binary one's complement)It is unary and has the effect of 'flipping bits'a = 0b0011 1100<br>~a = 1100 0011<br>~a = -61
<< (Binary left shift)The left operand's value is moved left by the number of bits specified by the right operanda = 0b0011 1100<br>b = a << 2<br>b = 240<br>b = 0b1111 0000
>> (Binary right shift)The right operand's value is moved right by the number of bits specified by the right operanda = 0b0011 1100<br>b = a >> 2<br>b = 15<br>b = 0b0000 1111

Membership Operators

Membership operators test for membership in a sequence such as strings, list or tuples.

OperatorDescriptionExample
inEvaluates to True if it finds a variable in the specified sequence, and False otherwise(x in y) is True when x is a member of sequence y.

python x = 2 y = [1, 2, 3] print(x in y) # True
not inEvaluates to True if it does not find a variable in the specified sequence, and False otherwise(x not in y) is True when x is not a member of sequence y.

python x = 4 y = [1, 2, 3] print(x not in y) # True

Identity Operators

Identity operators compare the memory locations of two objects.

OperatorDescriptionExample
isEvaluates to True if the variables on either side of the operator point to the same object, and False otherwise(x is y) is True when id(x) is equal to id(y).

python x = 1 y = 1 print(x is y) # True
is notEvaluates to False if the variables on either side of the operator point to the same object, and True otherwise(x is not y) is True when id(x) is not equal to id(y).

python x = 1 y = 1 print(x is not y) # False

Operators precendance

PEMDAS: Power Exponent Multiplication Divide Addition Substraction The following table list all the operators from highest precedence to the lowest:

OperatorDescription
**Exponentiation (raise to the power)
~, +, -Complement, unary plus and minus
*, /, %, //Multiply, Divide, Modulo and Floor Division
+, -Addition and Subtraction
>>, <<Right and Left bitwise shift
&Bitwise AND
^, |Bitwise exclusive 'OR' and 'OR'
<=, <>, >=Comparison operators
<, >, ==, !=Equality operators
=, %=, /=, //=, -=, +=, *=, **=Assignment operator
is, is not, in, not in, not, or, andMembership operators and Logical operators

Variable formatting

Three ways by which you can format a variable.

  • Using format() function and
main.py

  Example:
  a = 10, b = 20
  print("This value of a: {} and b: {}".format(a, b))
  # output: The value of a: 10 and b: 20

  • Using format() function with indexes and
main.py

  Example:
  a = 10, b = 20
  print("This value of b: {1} and a: {0}".format(a, b))
  # output: The value of b: 20 and a: 10

  • Using Shorthand of format() function[f]
main.py

  Example:
  a = 10, b = 20
  print(f"The value of a: {a} and b: {b}")
  # output: The value of a: 10 and b: 20

Conclusion

In conclusion, Python operators are fundamental tools for any developer. They allow you to perform a wide range of operations, from simple arithmetic calculations to complex logical evaluations. By mastering Python operators, you'll be better equipped to write efficient and readable code.

FAQs

  1. What are Python operators used for?

    Python operators are used to perform operations on variables and values. They are essential for tasks like arithmetic calculations, comparisons, and logical evaluations.

  2. How do I prioritize operators in Python expressions?

    Python follows operator precedence, where certain operators have higher priority than others. It's important to understand this order when writing complex expressions.

  3. Can I create custom operators in Python?

    Python doesn't allow you to create custom operators, but you can overload existing operators for custom classes.

  4. What is the difference between '==' and 'is' in Python?

    '==' is used to compare the values of two objects, while 'is' is used to check if two variables refer to the same object in memory.

  5. Where can I learn more about Python operators?

    You can explore Python's official documentation and various online tutorials to dive deeper into Python operators.