Python Operators – A Practical Guide for Beginners (2024)

This tutorial provides an in-depth overview of Python operators. There are various kinds of operators in Python including Arithmetic, Comparison, Assignment, Logical, Bitwise, Identity, and Membership operators. Here, you’ll learn their syntax and practice with numerous examples. You must clearly understand their meaning in Python in order to write better programs. Let’s explore what are they, what purpose they cater to, and how to use them.

Contents

Arithmetic operatorsArithmetic operator’s FAQsComparison operatorsSome FAQs on comparison operatorsLogical operatorsBitwise operatorsSome FAQs on bitwise operatorsAssignment operatorsAssignment operator FAQAdvanced Python operatorsIdentity operatorsMembership operators

What is an operator in Python?

Python operator is a symbol represented by a special character, gets the input from one or more operands, and performs a specific task.

Like many programming languages, Python reserves some special characters for acting as operators. Every operator carries out some operations such as addition, and multiplication to manipulate data and variables. The variables passed as input to an operator are known as operands.

>>> 7%43

In the above case, ‘%’ is the modulus operator that calculates the remainder of the division. The numbers ‘7’ and ‘4’ passed as input are the operands, whereas the number ‘3’ is the result of the action performed. We also recommend you read about keywords in Python.

Arithmetic operators

With arithmetic operators, we can do various arithmetic operations like addition, subtraction, multiplication, division, modulus, exponent, etc. Python provides multiple ways for arithmetic calculations like eval function, declare variable & calculate, or call functions. The table below outlines the built-in arithmetic operators in Python.

OperatorUsagePurpose
+a + bAddition – Sum of two operands
a – bSubtraction – Difference between the two operands
*a * bMultiplication – Product of the two operands
/a / bFloat Division – Quotient of the two operands
//a // bFloor Division – Quotient of the two operands (Without fractional part)
%a % bModulus – Integer remainder after division of ‘a’ by ‘b.’
Note: It is also known as the percent operator.
**a ** bExponent – Product of ‘a’ by itself ‘b’ times (a to the power of b)
Note: It is also known as the exponentiation operator.

Example-

a=7b=4print('Sum : ', a+b)print('Subtraction : ', a-b)print('Multiplication : ', a*b)print('Division (float) : ', a/b)print('Division (floor) : ', a//b)print('Modulus : ', a%b)print('Exponent : ', a**b)

Output-

Sum : 11Subtraction : 3Multiplication : 28Division (float) : 1.75Division (floor) : 1Modulus : 3Exponent : 2401

Arithmetic operator’s FAQs

What does the % sign mean in Python?

The modulus operation is the meaning of the % sign in Python. It takes two operands and returns the remainder of the two.

What does %= mean in Python?

The %= operator is an augmented form of the modulo or modulus operator. It first performs the modulus operation and then assigns the output to the left operand or the variable.

Comparison operators

In Python programming, comparison operators allow us to determine whether two values are equal or if one is higher than the other and then make a decision based on the result. The table below outlines the built-in comparison operators in Python.

OperatorUsagePurpose
>a > bGreater than – if theleft operand is greater, then it returns true.
<a < bLess than – if the left operand is less, then it returns true.
==a == bEqual to – if two operands are equal, then it returns true.
!=a != bNot equal to – if two operands are not equal, then it returns true.
>=a >= bGreater than or equal – True if theleft operand is greater or equal.
<=a <= bLess than or equal – True if the left operand is less than or equal.

Example-

a=7b=4print('a > b is',a>b)print('a < b is',a<b)print('a == b is',a==b)print('a != b is',a!=b)print('a >= b is',a>=b)print('a <= b is',a<=b)

Output-

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

Some FAQs on comparison operators

What does != Means in Python?

The != operator in Python means to compare two values that should not match. It checks for the inequality of two variables. It returns True if the values don’t match and False otherwise.

What do the symbols “=” and “==” mean in Python?

The meaning of the “=” symbol in Python is assigning some value to a variable. Whereas, the “==” symbol means to match two values for equality.

Logical operators

Logical Python operators enable us to make decisions based on multiple conditions. The operands act as conditions that can result in a true or false value.The outcome of such an operation is either true or false (i.e., a Boolean value).

However, not all of these operators return a boolean result. The ‘and’ and ‘or’ operators do return one of their operands instead of a pure boolean value. Whereas the ‘not’ operator always gives a real boolean outcome. Check the table and the example to know how these operators work in Python.

OperatorUsagePurpose
anda and bif ‘a’ is false, then ‘a’, else ‘b’
ora or bif ‘a’ is false, then ‘b’, else ‘a’
notnot aif ‘a’ is false, then True, else False

Example-

a=7b=4# Result: a and b is 4print('a and b is',a and b)# Result: a or b is 7print('a or b is',a or b)# Result: not a is Falseprint('not a is',not a)

Output-

a and b is 4a or b is 7not a is False

Bitwise operators

Bitwise Python operators process the individual bits of integer values.They treat them as sequences of binary bits.

We can use bitwise operators to check whether a particular bit is set. For example, IoT applications read data from the sensors based on whether a specific bit is set or not. In such a situation, these operators can help.

OperatorUsagePurpose
&a & bBitwise AND – compares two operands on a bit level.
It returns 1 if both the corresponding bits are 1
|a | bBitwise OR –compares two operands on a bit level.
It returns 1 if any of the corresponding bits is 1
~~aBitwise NOT – inverts all of the bits in a single operand.
^a ^ bBitwise XOR – compares two operands on a bit level.
It returns 1 if any of the corresponding bits is 1, but not both
>>a >> bRight shift – shifts the bits of ‘a’ to the right by ‘b’ no. of times.
<<a << bLeft shift – shifts the bits of ‘a’ to the left by ‘b’ no. of times.

Out of the above bitwise operators, Python xor has various applications such as swapping two numbers, in cryptography to generate checksum and hash.

Example-

Let’s consider the numbers 4 and 6 whose binary representations are ‘00000100’ and ‘00000110’. Now, we’ll perform the AND operation on these numbers.

a=4b=6#Bitwise AND: The result of 'a & b' is 4print('a & b is',a & b)

Output-

a & b is 4

The above result is the outcome of the following AND (‘&’) operation.

 0 0 0 0 0 1 0 0 & 0 0 0 0 0 1 1 0 ------------------ 0 0 0 0 0 1 0 0 (the binary representation of the number 4)

Some FAQs on bitwise operators

What does << mean in Python?

The << is one of the bitwise operators in Python that shifts the specified number of bytes to the left. It is useful in optimizing calculations such as quickly multiplying a number by a power of 2.

What does >> mean in Python?

In Python, the >> symbol means to move the bits from left to right. It is a special operator that not only extracts bits from a binary number but also has a use in basic encoding and decoding operations. For example, you can use it to encode an ASCII character into a binary number and then << to reverse the same.

Assignment operators

In Python, we can use assignment operators to set values into variables. The instruction a = 4 uses a primitive assignment operator that assigns the value 4 to the left operand.

Below is the list of available compound operators in Python. For example, the statement a += 4 adds to the variable and then assigns the same. It will evaluate to a = a + 4.

OperatorExampleSimilar to
= a = 4 a = 4
+= a += 4 a = a + 4
-= a -= 4 a = a – 4
*= a *= 4 a = a * 4
/= a /= 4 a = a / 4
%= a %= 4 a = a % 4
**= a **= 4 a = a ** 4
&= a &= 4 a = a & 4
|= a |= 4 a = a | 4
^= a ^= 4 a = a ^ 4
>>= a >>= 4 a = a >> 4
<<= a <<= 4 a = a << 4

Assignment operator FAQ

Python a &= b meaning?

The a &= b is a Python expression that uses two operands a and b joined by the &= operator. The meaning of such a statement is doing a bitwise AND operation between the corresponding bits of the two operands,i.e., a and b.

Advanced Python operators

Python also bundles a few operators for special purposes. These are known as advanced Python operators like the identity operator or the membership operator.

Identity operators

These operators enable us to compare the memory locations of two Python objects/variables. They can let us find if the objects share the same memory address. The variables holding equal values are not necessarily identical.

Alternatively, we can use these operators to determine whether a value is of a specific class or type. Refer to the below table to understand more about them.

OperatorPurposeUsage
isTrue – if both the operands refer to the same object, else returns Falsea is b (True if id(a) and id(b) are the same)
is notTrue – if the operands refer to different objects, False otherwisea is not b (True if id(a) and id(b) are different)

Example-

# Using 'is' identity operatora = 7if (type(a) is int): print("true")else: print("false")# Using 'is not' identity operatorb = 7.5if (type(b) is not int): print("true")else: print("false")

Output-

truetrue

Membership operators

Membership operators enable us to test whether a value is a member of other Python objects such as strings, lists, or tuples.

In C, a membership test requires iterating through a sequence and checking each value. But Python makes it very easy to establish membership as compared to C.

Also, note that this operator can also test against a Python dictionary but only for the key, not the value.

OperatorPurposeUsage
inTrue – if the value exists in the sequence7 in [3, 7, 9]
not inTrue – if the value doesn’t found in the sequence7 not in [3, 5, 9]

Example-

# Using Membership operatorstr = 'Python operators'dict = {6:'June',12:'Dec'}print('P' in str) print('Python' in str)print('python' not in str)print(6 in dict) print('Dec' in dict)

Output-

TrueTrueTrueTrueFalse

Conclusion – Python operators

This tutorial covered various Python operators, and their syntax, and described their operation with examples. Hence, it should now be easier for you to use operators in Python.

If you find something new to learn today, then do share it with others. And, follow us onour social media accounts to get notified of more such tutorials.

Best,

TechBeamers

Python Operators – A Practical Guide for Beginners (2024)

References

Top Articles
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 6053

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.