Python Operators (With Examples) (2024)

Operators are special symbols that perform operations on variables and values. For example,

print(5 + 6) # 11

Here, + is an operator that adds two numbers: 5 and 6.

Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Bitwise Operators
  6. Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,

sub = 10 - 5 # 5

Here, - is an arithmetic operator that subtracts two values or variables.

OperatorOperationExample
+Addition5 + 2 = 7
-Subtraction4 - 2 = 2
*Multiplication2 * 3 = 6
/Division4 / 2 = 2
//Floor Division10 // 3 = 3
%Modulo5 % 2 = 1
**Power4 ** 2 = 16

Example 1: Arithmetic Operators in Python

a = 7b = 2# additionprint ('Sum: ', a + b) # subtractionprint ('Subtraction: ', a - b) # multiplicationprint ('Multiplication: ', a * b) # divisionprint ('Division: ', a / b) # floor divisionprint ('Floor Division: ', a // b)# moduloprint ('Modulo: ', a % b) # a to the power bprint ('Power: ', a ** b) 

Output

Sum: 9Subtraction: 5Multiplication: 14Division: 3.5Floor Division: 3Modulo: 1Power: 49

In the above example, we have used multiple arithmetic operators,

  • + to add a and b
  • - to subtract b from a
  • * to multiply a and b
  • / to divide a by b
  • // to floor divide a by b
  • % to get the remainder
  • ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

# assign 5 to x var x = 5

Here, = is an assignment operator that assigns 5 to x.

Here's a list of different assignment operators available in Python.

OperatorNameExample
=Assignment Operatora = 7
+=Addition Assignmenta += 1 # a = a + 1
-=Subtraction Assignmenta -= 3 # a = a - 3
*=Multiplication Assignmenta *= 4 # a = a * 4
/=Division Assignmenta /= 3 # a = a / 3
%=Remainder Assignmenta %= 10 # a = a % 10
**=Exponent Assignmenta **= 10 # a = a ** 10

Example 2: Assignment Operators

# assign 10 to aa = 10# assign 5 to bb = 5 # assign the sum of a and b to aa += b # a = a + bprint(a)# Output: 15

Here, we have used the += operator to assign the sum of a and b to a.

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False. For example,

a = 5b =2print (a > b) # True

Here, the > comparison operator is used to compare whether a is greater than b or not.

OperatorMeaningExample
==Is Equal To3 == 5 gives us False
!=Not Equal To3 != 5 gives us True
>Greater Than3 > 5 gives us False
<Less Than3 < 5 gives us True
>=Greater Than or Equal To3 >= 5 give us False
<=Less Than or Equal To3 <= 5 gives us True

Example 3: Comparison Operators

a = 5b = 2# equal to operatorprint('a == b =', a == b)# not equal to operatorprint('a != b =', a != b)# greater than operatorprint('a > b =', a > b)# less than operatorprint('a < b =', a < b)# greater than or equal to operatorprint('a >= b =', a >= b)# less than or equal to operatorprint('a <= b =', a <= b)

Output

a == b = Falsea != b = Truea > b = Truea < b = Falsea >= b = Truea <= b = False

Note: Comparison operators are used in decision-making and loops. We'll discuss more of the comparison operator and decision-making in later tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False. They are used in decision-making. For example,

a = 5b = 6print((a > 2) and (b >= 6)) # True

Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.

OperatorExampleMeaning
anda and bLogical AND:
True only if both the operands are True
ora or bLogical OR:
True if at least one of the operands is True
notnot aLogical NOT:
True if the operand is False and vice-versa.

Example 4: Logical Operators

# logical ANDprint(True and True) # Trueprint(True and False) # False# logical ORprint(True or False) # True# logical NOTprint(not True) # False

Note: Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

OperatorMeaningExample
&Bitwise ANDx & y = 0 (0000 0000)
|Bitwise ORx | y = 14 (0000 1110)
~Bitwise NOT~x = -11 (1111 0101)
^Bitwise XORx ^ y = 14 (0000 1110)
>>Bitwise right shiftx >> 2 = 2 (0000 0010)
<<Bitwise left shiftx 0010 1000)

6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.

Identity operators

In Python, is and is not are used to check if two values are located at the same memory location.

It's important to note that having two variables with equal values doesn't necessarily mean they are identical.

OperatorMeaningExample
isTrue if the operands are identical (refer to the same object)x is True
is notTrue if the operands are not identical (do not refer to the same object)x is not True

Example 4: Identity operators in Python

x1 = 5y1 = 5x2 = 'Hello'y2 = 'Hello'x3 = [1,2,3]y3 = [1,2,3]print(x1 is not y1) # prints Falseprint(x2 is y2) # prints Trueprint(x3 is y3) # prints False

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.

Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).

In a dictionary, we can only test for the presence of a key, not the value.

OperatorMeaningExample
inTrue if value/variable is found in the sequence5 in x
not inTrue if value/variable is not found in the sequence5 not in x

Example 5: Membership operators in Python

message = 'Hello world'dict1 = {1:'a', 2:'b'}# check if 'H' is present in message stringprint('H' in message) # prints True# check if 'hello' is present in message stringprint('hello' not in message) # prints True# check if '1' key is present in dict1print(1 in dict1) # prints True# check if 'a' key is present in dict1print('a' in dict1) # prints False

Output

TrueTrueTrueFalse

Here, 'H' is in message, but 'hello' is not present in message (remember, Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1. Hence, 'a' in y returns False.

Also Read:

  • Precedence and Associativity of operators in Python
  • Python Operator Overloading
Python Operators (With Examples) (2024)

FAQs

What are the operators in Python with examples? ›

Python Bitwise Operators
OperatorNameExample
^XORx ^ y
~NOT~x
<<Zero fill left shiftx << 2
>>Signed right shiftx >> 2
2 more rows

What is the === in Python? ›

”===“ is a JavaScript operator that compares two things for equality. If the two things being compared are equal in value, it returns true. ”is” is a Python operator that compares the references of two things and returns whether they are the same.

What does |= mean in Python? ›

|= Performs Bitwise OR on operands and assign value to left operand. a|=b a=a|b. ^= Performs Bitwise xOR on operands and assign value to left operand.

What does \\ do in Python? ›

The \\ that you type in the source code is special syntax that means a single backslash in the actual string.

What are operators with example? ›

In other words, we can also say that an operator is a symbol that tells the compiler to perform specific mathematical, conditional, or logical functions. It is a symbol that operates on a value or a variable. For example, + and - are the operators to perform addition and subtraction in any C program.

What does *= in Python mean? ›

The = operator assigns the value on the right to the variable on the left. The += operator updates a variable by incrementing its value and reassigning it. The -= operator updates a variable by decrementing its value and reassigning it. The *= operator updates a variable by multiplying its value and reassigning it.

Is ++ allowed in Python? ›

In some other languages, there is even a special syntax ++ and -- for incrementing or decrementing by 1. Python does not have such a special syntax. To increment x by 1 you have to write x += 1 or x = x + 1 .

What is := in Python? ›

Each new version of Python adds new features to the language. For Python 3.8, the biggest change is the addition of assignment expressions. Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.

What does %= mean in Python? ›

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.

What does .__ do in Python? ›

The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.

What is '~' operator in Python? ›

PythonServer Side ProgrammingProgramming. The bitwise operator ~ (pronounced as tilde) is a complement operator. It takes one bit operand and returns its complement.

What does [:] do in Python? ›

It is done using the slicing operator [:]. The operator takes two arguments separated by a colon. The first argument specifies the index of the element where the slice starts and the second argument specifies the index of the element where the slice ends.

What does %% do in Python? ›

The Literal Percent Character ( %% )

The first percent character introduces a conversion specifier, and the second percent character specifies that the conversion type is % . >>> "Get %d%% off on %s today only!" % (30, "bananas") 'Get 30% off on bananas today only!

What is {} in Python? ›

In Python, `{}` and `[]` brackets are used to define different types of data structures: dictionaries and lists, respectively. 1. Curly Braces `{}`: - Used to define a dictionary in Python. - A dictionary is an unordered collection of key-value pairs, where each key must be unique.

What does '\ r do in Python? ›

In this article, we will explore what the carriage return “\r” does in Python. A carriage return is a simple escape character that operates similarly to \n. However, unlike \n, which moves the cursor to a new line, \r shifts the cursor to the beginning of the current line.

What are the basic list operators used in Python? ›

Basic list operations in Python include performing basic arithmetic on the numbers contained within a list, accessing elements of an existing list, replacing elements of a list, rearranging elements of a list, concatenating multiple lists together, and duplicating specific entries in a list.

What do you mean by the in operator in Python explain with an example? ›

The 'in' operator in Python is straightforward to use. It checks whether a value exists in a sequence (such as a list, tuple, or string) and returns a Boolean value: True if the value is in the sequence, and False if it's not.

What are the 3 Python logical operators? ›

Python has three Boolean operators, or logical operators: and , or , and not . You can use them to check if certain conditions are met before deciding the execution path your programs will follow. In this tutorial, you'll learn about the and operator and how to use it in your code.

Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6186

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.