0% found this document useful (0 votes)
20 views82 pages

phython-UNIT-I Notes Mar18

Uploaded by

217r1a0582
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views82 pages

phython-UNIT-I Notes Mar18

Uploaded by

217r1a0582
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

Prepared by A.

kirankumar
Assistant Professor
CMRTC
UNIT–I 8L
IntroductiontoPython:History,Features,Applications
,FirstPythonProgram,Variables,Data Types,
Numbers, Operators, Input and Outputstatements.
ControlStatements:ConditionalStatements,AWordo
nIndentation,LoopingStatements,the else Suite,
break, continue, pass, assert,return.
•What is Python?
•Python is a general purpose, dynamic-typed, high-level, interpreted and Object Oriented
programming language.

•Python is a Scripting Language ,and multipurpose Programming Language . It can be used


with web, enterprise, 3D CAD, etc.

•Python was invented by Guido Van Rossum in the year 1989, but it was introduced into the
market on 20th February 1991.

•Python is widely used in every technical field, such as Machine Learning,


Artificial Intelligence, Web Development, Mobile Application, Desktop Application, Scientific
Calculation, etc.

•Using Python, one can solve complex problems in less time with fewer lines of code.

•Python is Open Source which means its available free of cost.


•Python makes the development and debugging fast because there is
no compilation step included in Python development.

•Python supports multiple programming paradigms, like object-


oriented and functional programming or procedural.

•It provides extensive support libraries(Django for web


development, Pandas for data analytics etc)

•Websites like Instagram, Reddit, Mozilla, have been developed using


Python.
Python History
•The implementation of Python was started in December 1989
by Guido Van Rossum working on Project at CWI(Centrum Wiskunde
& Informatica ) in Netherland.
•In February 1991, Guido Van Rossum published the code (labeled
version 0.9.0).
•In 1994, Python 1.0 was released with new features like lambda, map,
filter, and reduce.

•In 2000,Python 2.0 added new features such as list comprehensions,


garbage collection systems.

•On December 3, 2008, Python 3.0 (also called "Py3K") was released.
It was designed to rectify the fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python
language, which was capable of Exception Handling and interfacing with
the Amoeba Operating System.

The following programming languages influence Python:


ABC language.
Modula-3

Python was named after the BBC TV show


Monty Python's Flying Circus.
Versions
The Python programming language was invented by Guido Van
Rossum in the year 1989. The first version of Python was released into
the market on 20th Feb 1991, later it was released with different
versions. The following table provides a list of versions released in the
Python.
S. No.Version Release Date
1 Python 1.0 January 1994
2 Python 1.5 December 31, 1997
3 Python 1.6 September 5, 2000
4 Python 2.0 October 16, 2000
5 Python 2.1 April 17, 2001
6 Python 2.2 December 21, 2001
7 Python 2.3 July 29, 2003
8 Python 2.4 November 30, 2004
10 Python 2.6 October 1, 2008
11 Python 2.7 July 3, 2010
12 Python 3.0 Feb. 13, 2009
13 Python 3.1 June 26, 2009
14 Python 3.2 Feb. 20, 2011
15 Python 3.3 Sept. 29, 2012
16 Python 3.4 March 17, 2014
17 Python 3.5 Sept. 13, 2015
18 Python 3.6 Dec. 23, 2016
19 Python 3.7 June 27, 2018
20 Python 3.8 Oct 14, 2019
21 Python 3.9 Oct 05, 2020
22 Python 3.10 Oct 04, 2021
22 Python 3.11.1 Dec 6 ,2022
Why the Name Python?
•There is a fact behind choosing the name Python. Guido van
Rossum was reading the script of a popular BBC comedy series "Monty
Python's Flying Circus". It was late on-air 1970s.
•Van Rossum wanted to select a name which unique, sort, and little-bit
mysterious. So he decided to select naming Python after the "Monty
Python's Flying Circus" for their newly created programming language.
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in
various fields such as machine learning, artificial intelligence, web
applications, etc. We define some popular frameworks and libraries of
Python as follows.
Web development (Server-side) - Django ,Flask, Pyramid, CherryPy
GUIs based applications - Tk, PyGTK, PyQt, etc.
Machine Learning - TensorFlow, PyTorch, Matplotlib, Scipy, etc.
Mathematics - Numpy, Pandas, etc.
Data Analytics-Pandas
Why Python
•Python increases your productivity. Python allows you to solve
complex problems in less time and fewer lines of code.
•Python becomes a solution in many areas across industries, from web
applications to data science and machine learning.
•Python is quite easy to learn in comparison with other programming
languages. Python syntax is simple and easy.
•Python has a large ecosystem that includes lots of libraries and
frameworks.
•Python is cross-platform. Python programs can run on Windows,
Linux, and macOS.
•Python developers are in high demand.
Where we use the Python
The Python programming language has a very wide range of
applications and few of them are listed below.
•BigData
•Data Science
•Artificial intelligence / Machine learning
•Mobile Apps
•Desktop Apps
•Web Apps
•Automation
•Hacking
•Testing and more...
•Python is a general-purpose language. It means that you can use
Python in various domains including
Python Features
1) Easy to Learn and Code
Python is very easy to learn the language as compared to other languages
like C, C#, Javascript, Java, etc. Python has few keywords, simple
structure, and a clearly defined syntax.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple
example, the hello world program you simply type print("Hello
World").
3) Interpreted Language
Python is an Interpreted Language because Python code is executed line
by line at a time. It makes debugging easy and portable.
4) High-Level Language
Python is a high-level language.It is easy to understand and read by
humans. When we write programs in Python, we do not need to
remember the system architecture, nor do we need to manage the
memory just concentrate on logic of program.
5)Large Standard Library
It provides a vast range of libraries for the various fields such as machine
learning,Artificial Intelligence, web developer,DataScience. There are
various machine learning libraries, such as Tensor flow, Pandas, Numpy,
Keras, , etc. Django, flask, pyramids are the popular framework for
Python web development.
6) Free and Open Source
Python is freely available for everyone. It is freely available on its
official website www.python.org. The open-source means, "Anyone can
download its source code without paying any penny.“
7) Object-Oriented Language
Python supports object-oriented language and concepts of classes and
objects. It supports inheritance, polymorphism, and encapsulation, etc.
The object-oriented procedure helps to programmer to write reusable
code
8)Portable language
Python language is a portable language. For example, if we have Python
code for windows and if we want to run this code on other platforms such
as Linux, Unix, and Mac then we do not need to change it, we can run this
code on any platform.
9)Dynamically Typed Language
Python is a dynamically-typed language. we don’t need to specify the type
of variable at the time of declaration.Interpreter automatically bind the
value with the particular datatype at runtime.
Ex: x=10
10)Extensible
Python is an Extensible language. We can write some Python code into C
or C++ language and also we can compile that code in C/C++ language.
11) GUI Programming Support
Graphical User Interface is used for the developing Desktop application.
Graphical User interfaces can be made using a module such as PyQt5,
PyQt4 ,Tk in python. PyQt5 is the most popular option for creating
12)Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc.
Python runs code line by line like C,C++ Java. It makes easy to debug
the code.
13)Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When
we assign some value to the variable, it automatically allocates the
memory to the variable at run time.
14). Embeddable
The code of the other programming language can use in the Python
source code. We can use Python source code in another programming
language as well. It can embed other language into our code.
Applications of python:
1. Web Applications: Python can be used to develop secure web
applications. Frameworks like Django, Flask, Pyramid etc are used to
design and develop web based applications.
2.Desktop GUI Applications:
The GUI stands for the Graphical User Interface, which provides a
smooth interaction to any application. Python provides a Tk GUI
library to develop a user interface.
Toolkits such as TK,Kivy, wxWidgets, PyQt, etc., are used to build
applications on several platforms.
3.Game Development:
Python is also used in the development of interactive games.
Popular games like Pirates of the Caribbean, Bridge commander use
Python programming.Gaming libraries like pygame, panda3D, PySoy,and
Cocos2D make the game development process easy.
4. Data Science
Data science involves data collection, data sorting, data analysis, and
data visualization. Some of the popular libraries that provide ease in the
data science process are TensorFlow, Pandas, and Socket learning.
5.Software Development:
Python is just the perfect option for software development. Popular
applications like Google, Netflix, and Reddit all use Python.
6.Machine Learning and Artificial Intelligence:
This is the era of Artificial intelligence where the machine can perform
the task the same as the human
Python language is the most suitable language for Artificial intelligence
or machine learning.
Some of the Libraries are Keras, SciPy, pandas, NumPy.
7.Web Scraping Application
Web scraping is an automated process used to extract information from
websites in an easier and faster way.
A wide range of libraries and tools like pandas, matplotlib, and Selenium
makes the web scraping process easy and efficient.
8.Image Processing: Python is known for its image processing
capabilities, which includes traversing and analysing any image pixel by
pixel.
Some of libraries are: Pillow, Blender and OpenCV etc.
9.Scientific Computing Application: For its amazing computational
power and simple syntax, python is used for scientific computing
applications. Python libraries like SciPy,Pandas, Matplotlib
and NumPy are best suited for scientific computations.
10.Block Chain:
Developing a simple blockchain using the Python Framework is one of
the most efficient applications of Python.
11. Business Applications
Python offers excellent security and scalability features that make it
perfect for delivering high-performance business applications. It has
inbuilt libraries and tools like:Odoo and Tryton.
E-commerce and ERP are an example of a business application
Note: Odoo is business management software that provides you with an
automated solution for your business process.
Tryton is easy-to-use open-source business software. It has fully
integrated features like financial accounting, sales, CRM, purchasing,
shipping, and the list goes on.
Python 2 vs. Python 3
•Python 2 uses print as a statement and used as print "something" to
print some string on the console. On the other hand, Python 3
uses print as a function and used as print("something") to print
something on the console.

•Python 2 uses the function raw_input() to accept the user's input. It


returns the string representing the value, which is typed by the user. To
convert it into the integer, we need to use the int() function in Python.

•On the other hand, Python 3 uses input() function which automatically
interpreted the type of input entered by the user. However, we can cast
this value to any type by using primitive functions (int(), str(), etc.).
•In Python 2, the implicit string type is ASCII, whereas, in Python 3,
the implicit string type is Unicode.

•Python 3 doesn't contain the xrange() function of Python 2. The


xrange() is the variant of range() function which returns a xrange object
that works similar to Java iterator. The range() returns a list for example
the function range(0,3) contains 0, 1, 2.

•There is also a small change made in Exception handling in Python 3.


It defines a keyword as which is necessary to be used. We will discuss
it in Exception handling section of Python programming tutorial.
First Python Program
print Hello World on the console.

Python provides us the two ways to run a program:


•Using Interactive interpreter prompt
• Using a script file
Interactive interpreter prompt
•Python provides us the feature to execute the Python statement one by
one at the interactive prompt.
•The interpreter prompt is best to run the single-line statements of the
code. It is not suitable to write multiple lines of code.
Steps:
•To open the interactive mode, open the terminal (or command prompt)
•It will open the following prompt where we can execute the Python
statement and check their impact on the console.
•After writing the print statement, press the Enter key.
Using a script file (Script Mode Programming)
Using the script mode, we can write multiple lines code into a file which
can be executed later. For this purpose, we need to open an editor like
notepad, create a file named and save it with .py extension, which stands
for "Python".
Steps:
Step - 1: Open the Python interactive shell, and click "File" then choose
"New", it will open a new blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.

Step - 3: After saving the code, we can run it by clicking "Run" or "Run
Module". It will display the output to the shell.
The output will be
shown as follows.
Variable:
•A Python Variable is a name given to memory location. Python variable
is also known as an identifier and used to hold value.
•Python Variable is containers that store values.
•In Python, we don't need to specify the type of variable.
•When a variable is defined, we must create it with a value. If the value
is not assigned the variable gives an error stating that variable is not
defined
Syntax
variable_name = value
Ex:
roll_no = 101
print('Student rollno is’,roll_no)

Output: Student rollno is 101


Rules for Python variables
A Python variable name must start with a letter or the underscore
character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
Variable in Python names are case-sensitive (name, Name, and NAME
are three different variables).
The reserved words(keywords) in Python cannot be used to name the
variable in Python.
Declaration and Initialization of Variables
Ex1:
# declaring the var
Number = 250
# display
print(type(Number))
print( Number)

Output:
<class 'int'>
250
Displaying data type of a variable
The Python programming language provides a built-in function type( ) to
display the data type of a variable

Syntax:
Type(variable name)
Ex:
a = 105
print(type(a))
a = 10.66
print(type(a))
a = 'rama'
print(type(a))
Python Variable Types
There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.
Local Variable
•A Variable declared with in the function is known as Local variable
Local variable have scope within the function.
•We can access local variable with in the function
•Local variable cannot be accessed outside the function.
Global Variables
•A variable declared outside the function is known as global variable .Its
Scope is in the entire program (global).
•global variable can be accessed inside or outside of the function.
•Python provides the global keyword to use global variable inside the
function.
Delete a variable
We can delete the variable using the del keyword. The syntax is given
below.
Syntax -
del <variable_name>
Ex:

# Assigning a value to x
x = 10
print(x)
# deleting a variable.
del x
print(x)
Defining and accessing local variables
Ex:1
# Declaring a function
def add():
# Defining local variables.
a = 20
b = 30
c = a+b
print(“The sum is “,c)
# Calling a function
add()

Output: 50
Ex2: Local variable
# Local variable
def greet():
message = 'Hello'
print('Local', message)
greet()

Output:
Local Hello
Ex :global variable
# declare global variable
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)

Output:
Local Hello
Global Hello
Multiple Assignment
Python allows us to assign a value to multiple variables in a single
statement, which is also known as multiple assignments.
We can apply multiple assignments in two ways
•Assigning single value to multiple variables
•Assigning different values to multiple variables.
Assigning single value to multiple variables:Python allows assigning a
single value to several variables simultaneously with “=” operators.
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
Assigning different values to multiple variables:
In Python, it is possible to define more than one variable using a
single statement. When multiple variables are created using a
single statement, the variables and their corresponding value must
be separated with a comma symbol “ ,”.
Eg:
a, b, c = 1, 10.2, “CMRTC"

print(a)
print(b)
print(c)
Output:
1
10.2
CMRTC
Can we use the same name for different types?
If we use the same name, the variable starts referring to a new value
and type.
Ex:
a = 10
a = “CMRTC"
print(a)
Object Identity
In Python, every created object identifies uniquely in Python. Python
provides the guaranteed that no two objects will have the same identifier.
The built-in id() function, is used to identify the object identifier
Ex:
# Object Identity
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a)) output:
140703137527176
140703137527176
What is datatype?
Data type specify the type of data that can be stored inside a variable.
num = 24
Here, 24 (an integer) is assigned to the num variable. So the data type of
num is of the int class.

Note:
•Since everything is an object in Python programming, data types are
actually classes and variables are instances(object) of these classes.
•Python is a dynamically typed language; hence we do not need to define
the type of the variable while declaring it. The interpreter implicitly
binds the value with its type.
type()
•Python enables us to check the type of the variable used in the program.
•Python provides the type() function to know the data-type of the
variable.
Ex: to define the values of different data types and checking its type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Output:

<class 'int'>
<class 'str'>
Standard data types
The data types defined in Python are given below.
Numbers (Numeric)
Sequence Type
Boolean
Set
Dictionary
Numeric Data type
•Numeric data type is used to hold numeric values.
•The integer, float, and complex values belong to a Python Numeric
data-type.
•They are defined as int, float and complex classes in Python.

•int - holds signed integers of non-limited length.


Ex:10 ,50,-100,-25
• float - holds floating decimal points and it's accurate up to 15 decimal
places.
Ex: 10.5
• complex - A complex number contains an ordered pair, i.e., x + iy
where x and y denote the real and imaginary parts.
Ex: 1+2j
•the isinstance() function is used to check an object belongs to a
particular class.
•Ex:print(" c is a complex number", isinstance(1+3j,complex))
Ex to illustrate Numeric datatype
num1 = 5
print(num1, 'is of type', type(num1))

num2 = 2.0
print(num2, 'is of type', type(num2))

num3 = 1+2j
print(num3, 'is of type', type(num3))
Output
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
Dictionary:
•Dictionary is a ordered collection of elements. It stores elements in
key/value pairs.
•Key can hold any primitive data type, whereas value is an arbitrary
Python object.
•In Python, the dictionary data type (data structure) has implemented
with a class known as dict
•The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
•If we want to store information about countries and their capitals, we
can create a dictionary with country names as keys and capitals as
values.
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, ...}
Note:
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
Access Dictionary Values Using Keys
The dictionary elements are organized based on the keys.
So we can access dictionary elements based on key
print(capital_city[‘India'])
Output: Delhi

Ex to illustrate Dictionary
# create a dictionary named capital_city
capital_city = {'India': 'Delhi', 'Italy': 'Rome', 'England': 'London'}
print(capital_city)

Output:

{'India': 'Delhi', 'Italy': 'Rome', 'England': 'London'}


Ex2:
d = {1:'Raju', 2:'Sita', 3:'Laxman', 4:'Sanjay'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
boolean
•Boolean type provides two built-in values, True and False.
• These values are used to determine the given statement true or false. It
denotes by the class bool.
•True can be represented by any non-zero value or 'T' whereas false can
be represented by the 0 or 'F
•Ex:
•# Python program to check the boolean type
• print(type(True))
• print(type(False))

Output:
•<class 'bool'>
•<class 'bool‘>
Set:
•Set is an unordered collection of elements of different data types.It has
unique elements.
•It is iterable, mutable(can modify after creation) and has no duplicate
elements.
•Set is defined by values separated by commas inside braces { }
•The order of elements stored in list is not fixed.The order of set of
elements can be changed
•The set data type (data structure) has implemented with a class known
as a set
•Sets do not have any repetition of identical elements.

•Note:
•Since sets are unordered collections, indexing has no meaning. Hence,
the slicing operator [] does not work.
•The set is created by using a built-in function set().
Creating Set
Syntax
set_name = {element_1, element_2, element_3, ...}
In Python, a set can also be created using the set( ) constructor. The
set() constructor takes only one argument.
Syntax
set_name = set((element_1, element_2, element_3, ...))
Accessing Elements of a set in Python
•In Python, the set elements are organized without any index values. So,
accessing individual elements of a set is not allowed.
•However, we can access the entire set using the name of the set.
Ex: print(set_name)

Ex1:
# Creating Empty set
set1=set()
set2={'Van Rossum',2,3,'Python'}
#Printing Set value
print(set2)
Output:
{3, 'Van Rossum', 2, 'Python'}
Ex:2
#Creating Set
student_data = {1, 'Ram', '2nd Year', 'CSE', 85.80}
print(type(student_data))
print(student_data)
Output:
<class 'set'>
{1, 85.8, 'Ram', '2nd Year', 'CSE'}
Ex3:
# create a set named student_id
student_id = {112, 114, 116, 118, 115}
# display student_id elements
print(student_id)
# display type of student_id
print(type(student_id))
Output:
{112, 114, 115, 116, 118}
<class 'set'>
Sequence datatype

A Sequence is an ordered collection of items, indexed by positive


integers.
It is a combination of mutable and immutable data types. There are
three types of sequence data type available in Python, they are:
Strings
Lists
Tuples
Python String Data Type
•The string can be defined as the sequence of characters represented in
the quotation marks.
•In Python, we can use single, double, or triple quotes to define a string.
For example:
# Defining string
name ='Python'
print(name)
message="Python for beginners"
print(message)
Output:
Python
Python for beginners
Ex: To illustrate String
student = {1,'Rama',"3rd Year",86.5}
print(student)
print(type(student))

Output:
{1, '3rd Year', 86.5, 'Rama'}
<class 'set'>
Python List Data Type
•List is an ordered collection of elements of different data types.
•The items stored in the list are separated with a comma (,) and enclosed
within square brackets [].
•Python Lists are similar to arrays in C.
•A single list may contain DataTypes like Integers, Strings, as well as
Objects.
•Lists are mutable, and hence, they can be altered even after their creation.
•All the elements of a list are ordered and they are indexed. Here, the
index starts from '0' (zero) and ends with 'number of elements - 1'.
Creating the List
Lists in Python can be created by just placing the sequence inside the
square brackets[]
Syntax:
list_name = [element_1, element_2, element_3, ...]
Ex:
languages = [“C++", "Java", "Python“]
Accessing elements from the List
•In order to access the list items refer to the index number.
•Use the index operator [ ] to access an item in a list. The index must be
an integer.
Syntax
list_name[index]
Ex:
languages = [“C++", "Java", "Python“]
Print[languages[0]]
Output:
C++

We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the list
in the same way as they were working with the strings.
Ex to illustrate List Data type
# Access List Items
languages = [“C++", "Java", "Python"]
# access element at index 0
print(languages[0])
# access element at index 2
print(languages[2])

Output:
C++
Python
Ex 2:
list1=[1,"hi","Python",2]
#Checking type of given list
print(type(list1))
#Printing the list1
print(list1)

Output:
<class 'list'>
[1, 'hi', 'Python', 2]
Python Tuple Data Type
•Tuple is same as list it contains the ordered collection of the items of
different data types
•The only difference is that tuples are immutable. Tuples once created
cannot be modified.
•The items of the tuple are separated with a comma (,) and enclosed in
parentheses ().
•A tuple is a read-only data structure as we can't modify the size and
value of the items of a tuple. They are indexed by integers.
Creating a Tuple
Syntax:
tuple_name = (element_1, element_2, element_3, ...)
For example:
tup= (1,”python”)

Note: Creation of Python tuple without the use of parentheses is known


Access Tuple Items
Similar to lists, we use the index number to access tuple items in Python
Syntax
tuple_name[index]
Ex1:
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
Output:
Initial empty Tuple:
()
Ex2:
# Creating a Tuple of string
Tuple1 = (‘Hello', ‘Python') Output: ('Hello', 'Python')
print(Tuple1)
Ex3:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup)) output: <class 'tuple'>
#Printing the tuple ('hi', 'Python', 2)
print (tup)
Operators
•Operators are used to perform operations on variables and values.
•Operator is a symbol used to perform arithmetical and logical
operations.
•For example, '+' is a symbol used to perform mathematical addition
operation.
Consider the expression a = 10 + 30 .
Here, variable 'a', values '10' and '30' are known as Operands and the
symbols '=' and '+' are known as Operators.

Note:
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
In python, we have 7 different types of operators, they are:
•Arithmetic Operators
•Comparison Operators
•Assignment Operators
•Logical Operators
•Bitwise Operators
•Membership Operators
•Identity Operators
While the first five are commonly used operators the last two i.e
Membership and Identity operators are exclusive to python.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on
operands like addition, subtraction, multiplication etc.
Operator Description
+ (Addition) It is used to add two operands.
It is used to subtract the second operand
- (Subtraction)
from the first operand
It returns the quotient after dividing the first
/ (divide)
operand by the second operand.
It is used to multiply one operand with the
* (Multiplication)
other.
It returns the reminder after dividing the first
% (reminder)
operand by the second operand.
As it calculates the first operand's power to
** (Exponent) the second operand, it is an exponent
operator.
// (Floor division) It provides the quotient's floor value, which
is obtained by dividing the two operands.
# Arithmetic Operators Ex Ex to illustrate Arithmetic Operators
a=7
b=2
print ('Sum: ', a + b) # addition output:
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
print ('floor Division: ', a // b)
Assignment Operators
Assignment operators are used to assign values to variables.
Ex: x = 5 Here, = is an assignment operator that assigns 5 to x.

Operator Description
Assigns right-hand side value to left-hand side variable
= (Assignment)
Ex: a = 10
Adds right operand to the left operand and assign the
+= (Add and Assign)
result to left operand Ex: If a = 10, b = 20 => a+ = b will
be equal to a = a+ b and therefore, a = 30.
Subtracts right operand from the left operand and assign
-=(Subtract and Assign) the result to left operand Ex: if a = 20, b = 10 => a- = b
will be equal to a = a- b and therefore, a = 10.
Multiplies right operand with the left operand and assign
*=(Multiply and Assign)
the result to left operand Ex: if a = 10, b = 20 => a* = b
will be equal to a = a* b and therefore, a = 200.
Divides left operand with the right operand and assign
/=(Division and Assign) the result to left operand Ex: if a = 20, b = 10 => a /= b
will be equal to a = a /b and therefore, a = 0.
Ex To illustrate Assignment Operators
# assignment operators
a = 10
b=5
print("=",a) output:
a += b
print("+=",a)
a*=b
print("*=",a)
a-=b
print("/=",a)
a/=b
Comparision operators:
Comparison operators compare two values/variables and return a
boolean value: True or False
Ex: a = 5 b =2 print (a > b) output: True
Here, the > comparison operator is used to compare whether a is
greater than b or not.
Operator Description
If the value of two operands is equal, then the condition
==
becomes true.
If the value of two operands is not equal, then the
!=
condition becomes true.
The condition is met if the first operand is smaller than
<=
or equal to the second operand.
The condition is met if the first operand is greater than
>=
or equal to the second operand.
If the first operand is greater than the second operand,
>
then the condition becomes true.
If the first operand is less than the second operand, then
<
the condition becomes true.
Ex To illustrate Comparison Operators
a=5
b=2
# equal to operator
print( a == b)
# not equal to operator
print( a != b)
# greater than operator
print(a > b)
# less than operator
print( a < b)
# greater than or equal to operator
print(a >= b)
# less than or equal to operator
print(a <= b)
Logical operators
•Logical operators are used to check whether an expression is True or
False. Logical operators are used to perform Logical operations
•Python has three logical operators
•and
•or
•not
•Sometimes, you may want to check multiple conditions at the same
time. To do so, you use logical operators.
•They are used in decision-making.
For example: a = 5 b = 6 print((a > 2) and (b >= 6)) output: True

Operator Description
and True only if both the operands are True
or True if at least one of the operands is True
not True if operand is false
Ex To illustrate Logical Operators
#logical operators
a = 10
b=3
c = 20
print(a < b and a > c)
print(a < b or a > c)
print(not a > b)

Output:
False
False
False
bitwise operators
The bitwise operators are used to performs bit by bit operation.
let's consider two variables a with value 10 equivalent binary value is
1010, b with value 15 equivalent binary value is 1111.

Operator Description
Result bit 1,if both operand bits are 1;otherwise results
& (Bitwise AND)
bit 0. x & y
Result bit 1,if any of the operand bit is 1; otherwise
|(Bitwise OR)
results bit 0. x | y
~(Bitwise NOT) inverts individual bits. ~x
Results bit 1,if any of the operand bit is 1 but not both,
^(Bitwise XOR) otherwise .results bit 0. x ^ y

The left operand’s value is moved toward right by the


>>(Bitwise right shift)
number of bits .specified by the right operand. x>>
<<(Bitwise left shift) The left operand’s value is moved toward left by the
number of bits .specified by the right operand. x<<
Ex to illustrate bitwise operators:
# bitwise operators
a = 10
b=4
# bitwise AND
print("a & b =", a & b)
# bitwise OR
print("a | b =", a | b)
# bitwise NOT
print("~a =", ~a)
#bitwise XOR
print("a ^ b =", a ^ b)
Identity Operators
identity operators are used to comparing the memory locations of two
objects or variables. There are two identity operators in Python.

Operator Description
Returns True if the variables on either side of the
Is (is identical) operator point to the same object otherwise returns
False. a is b
Returns False if the variables on either side of the
is not (is not identical) operator point to the same object otherwise returns
True. a is not b

# identical operators
a = 10
b=3
print(a is b)
print(a is not b) Output: False
True
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).
Operator Description
in True if value/variable is found in the sequence. 5 in x.
True if value/variable is not found in the sequence. 5 not
not in
in x.

Ex:
# Member ship operators
x = 'Hello world'
print('H' in x)
print('welcome' not in x)
Output:
True
True

You might also like