Python Operators: The Building Blocks of Code

Python has several types of operators. Mathematical, Assignment, Comparison, Logical, Identity, Membership, Bitwise operators.

Topics: ,

Greetings, fellow data enthusiasts! Today, we’ll dive into the world of Python operators. These are the symbols that tell Python what operations to perform on variables and values. Think of them as the gears that keep the engine of your code running smoothly.

In this short read, we will learn about operators. Because there are several types of operators in Python, they will be presented in tabular form. They are self-explanatory.

Types of Operators

1. Mathematical Operations with Operators

OperationOperatorExampleOutput
Addition+a=8,b=4 a + b12
Subtractiona=8,b=4 a - b4
Multiplication*a=8,b=4 a * b32
Modulus%a=8,b=4 a % b0
Division/a=8,b=4 a / b2.0
Floor Division//a=8,b=4 a // b2
Exponential**a=8,b=4 a ** b4096

1. Concatenation

  • The operator (+) is used to join the second and first elements.
  • For example, [1,3,4] + [1,1,1] equals [1,3,4,1,1,1].
  • We can concatenate all other sequences in the same way.

Merge two lists with the ‘+’ operator

Python
Python
Python
# Merge  two lists with '+' operator.
a=[1,3,4]
b=[1,1,1]
print(a+b)
Output
[1, 3, 4, 1, 1, 1]

Merge two tuples with the + operator

Python
Python
Python
# Merge two tuples with + opertor.
a=(1,3,4)
b=(1,1,1)
a+b
Output
(1, 3, 4, 1, 1, 1)
Python
Python
Python
# Merge two Strings with + opertor.
tree='pine' 
fruit='apple'
tree + fruit
Output
'pineapple'

2. Repeat

  • The operator (*) is used to repeat a sequence n a number of times.
  • For example, (1,2,3) * 3 equals (1,2,3,1,2,3,1,2,3).
  • This also works with sequences that aren’t tuples.

Use the * operator to repeat stored items

Python
Python
Python
# Use * operator to 
a=[1,3,4]
a*3
Output
[1, 3, 4, 1, 3, 4, 1, 3, 4]
Python
Python
Python
# multiply tuple by 3
b=(4,5,6)
b*3
Output
(4, 5, 6, 4, 5, 6, 4, 5, 6)

2. Assignment Operators

OperatorsExampleExplanation
=a=10a = 10
+=a+=10a = a+10
-=a-=10a = a-10
%=a%=10a = a%10
*=a*=10a = a*10
/=a/=10a = a/10
** =a**=10a = a**10
//=a//=10a = a//10
&=a&=10a = a&10
|=a|=10a = a|10
^=a^=10a = a^10
>>=a>>=10a = a>>10
<<=a<<=10a = a<<10
Python
Python
Python
# Use assignment operator
a=25
print(a)
Output
25
Python
Python
Python
# Use Addition Shorthand
a += 10
print(a)
Output
35
Python
Python
Python
# Use Multiplication Shorthand
a *= 10
print(a)
Output
10
Python
Python
Python
# Use Substraction Shorthand
a -= 10
print(a)
Output
25
Python
Python
Python
# Use modulo Shorthand
a %= 2
print(a)
Output
1
Python
Python
Python
# Use Power of number Shorthand
a **= 10
print(a)
Output
10000000000
Python
Python
Python
# Use Division Shorthand
a /= 10
print(a)
Output
1000000000.0

3. Comparison Operators

OperatorsOperationExplanation
==Equal toa == b
!=Not Equal toa != b
>Greater Thana > b
<Less Thana < b
>=Greater Than or Equal toa >= b
<=Less Than or I’m toa <= b
Python
Python
Python
# Comparing if 4 is equal to 5
4==5
Output
False
Python
Python
Python
# Comparing if 2 is not equal to 1
2!=1
Output
True
Python
Python
Python
# Comparing if 2 is greater than 1
2>1
Output
True
Python
Python
Python
# Comparing if 4 is equal to 4
4==4
Output
True

4. Logical Operator

OperatorsExplanationExample
andIt returns True if both statements are true.a > b and b > c
orIt returns if one or both of the statements are true.a < b or b > c
notReverses the Resultnot(a > c)

1. and operator

Python
Python
Python
# Declaring some integers.
a=10
c=15
b=20
# chaining comparisons.
c>a and c<b
Output
aTrue
Python
Python
Python
# chaining comparisons.
c>a and c>b
Output
False
Python
Python
Python
a# Using and operator.
True and True



Output
True
Python
Python
Python
# Using and operator.
True and False
Output
False

2. or operator

Python
Python
Python
# Using or operator
True or False
Output
True
Python
Python
Python
# Using or operator
False or False
Output
False
Python
Python
Python
# chaining or operator
c>a or c>b
Output
True

3. not operator

Python
Python
Python
# Using Not Operator with and
not True and False
Output
False
Python
Python
Python
# Using Not Operator with or
not True or False
Output
False
Python
Python
Python
# Using not operator with greater than b.
not a>b
Output
True
Python
Python
Python
# Using not operator with lesser than b.
not a<b
Output
False

5. Identity Operator

OperatorsExplanationExample
isIf Both given objects do not hold the same value, it will Return Truea is c
is notIf Both given objects do not hold the same value, it will return Truea is not c
Python
Python
Python
a=10
c=15
b=10
d=25
# Check if a is b , it's checked with id() function.
a is b
Output
True
Python
Python
Python
# Check if b is c , it's checked with id() function.
b is c
Output
False
Python
Python
Python
# Check if a is not c , it's checked with id() function.
a is not c



Output
True
Python
Python
Python
# Check if b is not c , it's checked with id() function.
b is not c
Output
True

6. Operators of Memberships

  • The membership operators (in) and (not in) are used to determine whether an item is present in the sequence. They either return True or False.
  • For example, the statement ‘la’ in “Manilla” evaluates to True, while the statement ‘a’ in “all” evaluates to False.
OperatorsExplanationExample
inIf the given value is not available in the collection,It will Return Truea in c
not inan in ca not in c
Python
Python
Python
# find 'pine' in fruit
# use membership operator 'in'.
fruit='pineapple'
'pine' in fruit
Output
True
Python
Python
Python
# find 'app' in fruit
'app' in fruit
Output
True
Python
Python
Python
# find 'banana' in fruit.
'banana' not in fruit

Output
True
Python
Python
Python
# find 'ineapp' in fruit.
'inepp' not in fruit
Output
False

7. Bitwise Operator

NameOperatorsDescription
AND&Returns 1 if both bits are 1
OR|Returns 1 if one or both bits are 1
Left Shift(Zero fill)<<Shifts bits to left by putting zeros from right and left end bit is deleted
Signed Right Shift>>Shifts bits to right by putting numbers copied from right to left and rightend bit is deleted
XOR^Returns 1 if only one bit is 1 and returns zero if both bits are same
NOT~Inverts Every bit
Python
Python
Python
# Using bitwise and
a = 10
b = 4
print('AND')
print( bin(a) , '\t' , bin(b) )
print("a & b =", a & b)
Output
AND
0b1010 	 0b100
a & b = 0
Python
Python
Python
# Using bitwise or
print('OR')

print( bin(a) , '\t' , bin(b) )

print("a | b =", a | b)
Output
OR
0b1010 	 0b100
a | b = 14
Python
Python
Python
# using bitwise not
print('NOT')

print( bin(a) , '\t' , bin(b) )

print("~a =", ~a)
Output
NOT
0b1010 	 0b100
~a = -11
Python
Python
Python
# using bitwise xor
print('XOR')

print( bin(a) , '\t' , bin(b) )

print("a ^ b =", a ^ b)
Output
XOR
0b1010 	 0b100
a ^ b = 14

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Hypothesis Testing: A Comprehensive Overview

    This article delves into the application of hypothesis testing across diverse domains

  • Versions of ANCOVA (Analysis Of Covariance) with python

    To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating Average rating 0 / 5. Vote count: 0 No votes so far! Be the first to rate this post.

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python Functions

    Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…

  • Quiz Challenge: Basics with Python [Questions]

    Solve These Questions in Following Challange

  • Introducing Plethora of Stable Diffusion models: Part 1

    Generate AI images as good as DALL-E completely offline.

Instagram
WhatsApp
error: Content is protected !!