Skip to main content
PYTHON PROGRAMMING
2 April 2022 2
What is Python?
• Python is a popular programming language.
• It was created by Guido van Rossum, and released in 1991.
It is used for:
• Web development (server-side),
• Software development,
• Mathematics,
• System scripting.
2 April 2022 3
What is Python
• Python is a general purpose, dynamic, high-level, and interpreted programming language.
• It supports Object Oriented programming approach to develop applications.
• It is simple and easy to learn and provides lots of high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
2 April 2022 4
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems.
• It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software development.
2 April 2022 5
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.
2 April 2022 6
Why learn Python?
• Easy to use and Learn
• Expressive Language
• Interpreted Language
• Object-Oriented Language
• Open Source Language
• Extensible
• Learn Standard Library
• GUI Programming Support
• Integrated
• Embeddable
• Dynamic Memory Allocation
• Wide Range of Libraries and Frameworks
2 April 2022 7
Python Features
1) Easy to Learn and Use
•Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.
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"). It will take only one line to execute, while Java
or C takes multiple lines.
3) Interpreted Language
•Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
2 April 2022 8
Python Features
4) Cross-platform Language
•Python can run equallyon different platforms such as
Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable
language.
5) Free and Open Source
•Python is freely available for everyone. It is freely
available on its official website www.python.org
6) Object-Oriented Language
•Python supports object-oriented language and concepts of
classes and objects come into existence. It supports inheritance, polymorphism, and
encapsulation, etc.
7) Extensible
•It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our Python code.
2 April 2022 9
Python Features
8) Large Standard Library
•It provides a vast range oflibraries for the various fields such as machine learning, web developer, and also for the
scripting. Django, flask, pyramids are the popular framework for Python web development.
9) GUI Programming Support
•Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries
which are used for developing the web application.
10) Integrated
•It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++
Java.
11. Embeddable
•The code of the other programming language can use in the Python source code.
12. Dynamic Memory Allocation
•In Python, we don't need to specify the data-type of the variable.
2 April 2022 10
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 is also versatile and widely used in every technical field, such as Machine Learning
• , Artificial Intelligence
• , Web Development, Mobile Application
• , Desktop Application, Scientific Calculation, etc.
Python Version List
Python Version Released Date Python Version Released Date
Python 1.0 January 1994 Python 2.7 July 3, 2010
Python 1.5 December 31, 1997 Python 3.0 December 3, 2008
Python 1.6 September 5, 2000 Python 3.1 June 27, 2009
Python 2.0 October 16, 2000 Python 3.2 February 20, 2011
Python 2.1 April 17, 2001 Python 3.3 September 29, 2012
Python 2.2 December 21, 2001 Python 3.4 March 16, 2014
Python 2.3 July 29, 2003 Python 3.5 September 13, 2015
Python 2.4 November 30, 2004 Python 3.6 December 23, 2016
Python 2.5 September 19, 2006 Python 3.7 June 27, 2018
Python 2.6 October 1, 2008 Python 3.8 October 14, 2019
2 April 2022 11
2 April 2022 12
Python Libraries and Frameworks
Python consists of vast libraries and various frameworks.
•TensorFlow - It is an artificial intelligence library which allows us to create large scale AI based
projects.
•Django - It is an open source framework that allows us to develop web applications. It is easy,
flexible, and simple to manage.
•Flask - It is also an open source web framework. It
is used to develop lightweight web
applications.
•Pandas - It is a Python library which is used to perform scientific computations.
•Keras - It is an open source library, which is used to work around the neural network.
2 April 2022 13
2 April 2022 14
1) Web Applications
• We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser, etc. One of Python web-framework named Django is used on Instagram.
• Django and Pyramid framework(Use for heavy applications)
• Flask and Bottle (Micro-framework)
• Plone and Django CMS (Advance Content management)
2 April 2022 15
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.
•Tkinter or Tk
•wxWidgetM
•Kivy (used for writing multitouch applications )
•PyQt or Pyside
2 April 2022 16
3) Console-based Application
• Console-based applications run from the command-line or shell.
• These applications are computer program which are used commands to execute.
• This kind of application was more popular in the old generation of computers.
• Python can develop this kind of application very effectively. .
2 April 2022 17
4) Software Development
• Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.
• SCons is used to build control.
• Buildbot and Apache Gumps are used for automated continuous compilation and testing.
• Round or Trac for bug tracking and project management.
2 April 2022 18
5) Scientific and Numeric
• 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.
• Implementing machine learning algorithms require complex mathematical calculation.
• Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-
learn, etc.
• Few popular frameworks ofmachine libraries are given below.
• SciPy
• Scikit-learn
• NumPy
• Pandas
• Matplotlib
2 April 2022 19
6) Business Applications
• Business Applications differ from standard applications.
• E-commerce and ERP are an example of a business application.
• This kind of application requires extensively, scalability and readability, and Python provides
all these features.
• Python provides a Tryton platform which is used to develop the business application.
2 April 2022 20
7) Audio or Video-based Applications
• Python is flexible to perform multiple tasks and can be used to create multimedia applications.
• Some multimedia applications which are made by using Python are TimPlayer, cplay, etc.
• The few multimedia libraries are given below.
• Gstreamer
• Pyglet
• QT Phonon
2 April 2022 21
8) 3D CAD Applications
• The CAD (Computer-aided design) is used to design engineering related architecture.
• It is used to develop the 3D representation of a part of a system.
• Python can create a 3D CAD application by using the following functionalities.
• Fandango (Popular )
• CAMVOX
• HeeksCNC
• AnyCAD
• RCAM
2 April 2022 22
9) Enterprise Applications
• Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
2 April 2022 23
10) Image Processing Application
• Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.
• OpenCV
• Pillow
• SimpleITK
2 April 2022 24
How to Install Python (Environment Set-up)
Installation on Windows
•Visit the link https://www.python.org/downloads/
•to download the latest release of Python
•In this process, we will install Python 3.8.6 on our Windows operating system
•When we click on the above link, it will bring us the following page.
Step - 1: Select the Python's version to download.
Step - 2: Click on the Install Now Step - 3 Installation in Process
Step - 1: Select the Python's version to download.
2 April 2022 25
Step - 2: Click on the Install Now
• Double-click the executable file,
which is downloaded; the following
window will open. Select Customize
installation and proceed. Click on the
Add Path check box, it will set the
Python path automatically.
2 April 2022 26
Step - 3 Installation in Process
2 April 2022 27
Cont….
• Now, try to run python on the command prompt. Type the command python -
version in case of python3.
2 April 2022 28
Python
Developme
nt Cycle
2 April 2022 29
2 April 2022 30
Python Development Cycle
• Python's development cycle is dramatically shorter than that of traditional tools.
• In Python, there are no compile or link steps -- Python programs simply import modules at
runtime and use the objects they contain.
• Because of this, Python programs run
immediately after changes are made.
• And in cases where dynamic module reloading can be used, it's even possible to change and
reload parts of a running program without
stopping it at all.
2 April 2022 31
Python Syntax
Execute Python Syntax
•Python syntax can be executed by writing directly in the Command Line:
>>> print("Hello, World!") Hello, World!
•by creating a python file on the server, using the .py file extension, and running it
in the Command Line:
C:UsersYour Name>python myfile.py
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
Example
if5 > 2:
print("Five is greater than two!")
Note: Python will give you an error if you skip the
indentation:
2 April 2022 32
Input and Output in Python
How to Take Input from User in Python
•To do this Python provides an input() function.
Syntax:
input('prompt')
where prompt is an optional string that is displayed on the string at the
time of taking input.
2 April 2022 33
2 April 2022 34
Example 1: Python get user input with a message
# Taking input from the user name
= input("Enter your name: ")
# Output
print("Hello, " + name)
print(type(name))
Output:
Enter your name: GFG Hello,
GFG
<class 'str'>
2 April 2022 35
Example 2: Integer input in Python
# Taking input from the user as integer
num = int(input("Enter a number: "))
add = num + 1
# Output print(add)
Output:
Enter a number: 25 26
2 April 2022 36
Output using print() function
Syntax: print(value(s), sep= ‘ ‘, end = ‘n’, file=file, flush=flush)
Parameters:
•value(s) : Any value, and as many as you like. Will be converted to string
before printed
•sep=’separator’ : (Optional) Specify how to separate the objects, if there
is more
than one. Default :’ ‘
•end=’end’: (Optional) Specify what to print at the end. Default : ‘n’
•file : (Optional) An object with a write method. Default :sys.stdout
•flush : (Optional) A Boolean, specifying if the output is flushed (True) or
buffered (False). Default: False
•Returns: It returns output to the screen.
2 April 2022 37
String Literals
• String literals in python’s print statement are primarily used to format or design how a specific
string appears when printed using the print() function.
• n : This string literal is used to add a new blank line while printing a statement.
• “” :An empty quote (“”) is used to print an empty line.
Example:
print(“ComputerScience n is best for DSA Content.")
Output:
ComputerScience
is best for DSA Content.
2 April 2022 38
end= ” ” statement
• The end keyword is used to specify the content that is to be printed at the end of the execution
of the print() function.
• By default, it is set to “n”, which leads to the change of line after the
execution of print()
statement.
Example: Python print() without new line.
# This line will automatically add a new line before the # next print statement
print (“St Martins is the best platform for DSA content")
# This print() function ends with "**" as set in the end argument.
print (" St Martins is the best platform for DSA content", end= "**") print("Welcome to
GFG")
Output:
St Martins is the best platform for DSA content
St Martins is the best platform for DSA content**Welcome to GFG
2 April 2022 39
Separator
• The print() function can accept any number of positional arguments.
• These arguments can be separated from each other using a “,” separator.
• These are primarily used for formatting multiple statements in a single print()
function.
Example:
b = "Engineering" print("St.Martin's", b , "College")
Output:
St.Martin's Engineering College
2 April 2022 40
Example: Python Print Output
# Python program to demonstrate #
print() method
print("GFG")
# code for disabling the softspace feature
print('G', 'F', 'G’)
Output
GFG G F G
2 April 2022 41
Formatting Output
Using formatted string literals
•We can use formatted string literals, by starting a string with f or
F before opening quotation marks or triple quotation marks.
•In this string, we can write Python expressions between { and } that
can refer to a variable or any literal value.
2 April 2022 42
Example: Python String formatting using F string
# Declaring a variable name = "Gfg"
# Output
print(f'Hello {name}! How are
you?’)
Output:
Hello Gfg! How are you?
2 April 2022 43
Using format()
• We can also use format() function to format our output to make it look
presentable.
• The curly braces { } work as placeholders.
• We can specify the order in which variables occur in the output.
2 April 2022 44
Example: Python string formatting using format() function
# Initializing variables a = 20
b = 10
# addition sum = a + b
# subtraction sub = a- b
# Output
print('The value of a is {} and b is {}'.format(a,b)) print('{2} is
the sum of {0} and {1}'.format(a,b,sum)) print('{sub_value} is
the subtraction of {value_a} and
{value_b}'.format(value_a = a , value_b = b, sub_value = sub))
Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10
2 April 2022 45
Using %Operator
• We can use ‘%’ operator. % values are replaced with zero or more value
of elements.
• Theformatting using% is similar to that of ‘printf ’
in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
2 April 2022 46
Example:
# Taking input from the user
num = int(input("Enter a value: "))
add = num + 5
# Output
print("The sum is %d" %add)
Output:
Enter a value: 50 The sum is 55
2 April 2022 47
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
2 April 2022 48
Creating a Comment
• Comments starts with a #, and Python will ignore them:
Example
#This is a comment print("Hello, World!")
• Comments can be placed at the end of a line, and Python will ignore the
rest of the line:
Example
print("Hello, World!") #This is a comment
2 April 2022 49
Multi Line Comments
• Python does not really have a syntax for multi line comments.
• To add a multiline comment you could insert a # for each line:
Example
#This is a comment #written in
#more than just one line print("Hello, World!")
2 April 2022 50
Python Variables
Variables
•Variables are containers for storing data values.
Creating Variables
•Python has no command for declaring a variable.
•A variable is created the moment you first assign a value to it.
Example
x = 5
y = "Rajalingam" print(x)
print(y) Output
5
Rajalingam
2 April 2022 51
Cont…
• Variables do not need to be declared with any particular type, and can
even change type after they have been set.
Example
x = 4 # x is of type int
x = "Computer Science" # x is now of type str print(x)
Output:
4
Computer Science
2 April 2022 52
Casting Variable
• If you want to specify the data type of a variable, this can be done with
casting.
Example:
x = str(3) # x will be '3' y = int(3) # y will be 3
z = float(3) # z will be 3.0
Output:
3
3
3.0
2 April 2022 53
Get the Type
• You can get the data type of a variable with the type() function.
Example
x = 5
y = "Dr. B.Rajalingam" print(type(x)) print(type(y))
Output:
<class 'int'>
<class 'str'>
2 April 2022 54
Single or Double Quotes?
• String variables can be declared either by using single or double
quotes:
Example
x = “Rajalingam" # is the same as x = 'Rajalingam’
Print(x)
Output:
Rajalingam
2 April 2022 55
Case-Sensitive
• Variable names are case-sensitive.
Example
This will create two variables: a =
4
A = “Rajalingam"
#A will not overwrite a
Output:
4
Rajalingam
2 April 2022 56
Python Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different things.
• Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
2 April 2022 57
Getting the Data Type
• You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x: x = 5
print(type(x))
Output:
<class 'int'>
2 April 2022 58
Setting the Data Type
• In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
2 April 2022 59
Example
Example 1
x = "Hello World" #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
Hello World
<class 'str'>
2 April 2022 60
Example
Example 2
x = 20
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
20
<class 'int'>
2 April 2022 61
Example
Example 3
x = 20.5
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
20.5
<class 'float'>
2 April 2022 62
Example
Example 4
x = 1j #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
lj
<class 'complex'>
2 April 2022 63
Example
Example 5
x = ["apple", "banana", "cherry"]
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
['apple', 'banana', 'cherry’]
<class 'list'>
2 April 2022 64
Example
Example 6
x = ("apple", "banana", "cherry")
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
('apple', 'banana', 'cherry’)
<class 'tuple'>
2 April 2022 65
Example
Example 7
x = range(6) #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
range(0, 6)
<class 'range'>
2 April 2022 66
Example
Example 8
x = {"name" : "John", "age" : 36}
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
{'name': 'John', 'age': 36}
<class 'dict'>
2 April 2022 67
Example
Example 9
x = {"apple", "banana", "cherry"}
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
{'cherry', 'banana', 'apple’}
<class 'set'>
2 April 2022 68
Example
Example 10
x = frozenset({"apple", "banana", "cherry"})
#display x:
print(x)
#display the data type of x: print(type(x))
Output:
frozenset({'apple', 'cherry', 'banana’})
<class 'frozenset'>
2 April 2022 69
Example
Example 11 x = True
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
True
<class 'bool'>
2 April 2022 70
Example
Example 12
x = b"Hello" #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
b'Hello’
<class 'bytes'>
2 April 2022 71
Example
Example 13
x = bytearray(5) #display x:
print(x)
#display the data type of x: print(type(x))
Output:
bytearray(b'x00x00x00x00x00’)
<class 'bytearray'>
2 April 2022 72
Example
Example 14
x = memoryview(bytes(5)) #display
x:
print(x)
#display the data type of x:
print(type(x))
Output:
<memory at 0x14cff7cd9a00>
<class 'memoryview'>
2 April 2022 73
Setting the Specific Data Type
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
2 April 2022 74
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
2 April 2022 75
Python Numbers
• To verify the type of any object in Python, use the type() function:
Example
x = 1
y = 2.8
z = 1j print(type(x)) print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
2 April 2022 76
Int
•Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x)) print(type(y)) print(type(z))
Output
<class 'int'>
<class 'int'>
<class 'int'>
2 April 2022 77
Float
• Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x)) print(type(y)) print(type(z))
Output
<class 'float'>
<class 'float'>
<class 'float'>
2 April 2022 78
Complex
•Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j z = -5j
print(type(x)) print(type(y)) print(type(z))
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
2 April 2022 79
Type Conversion
• You can convert from one type to another with the int(), float(), and
complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex #convert
from int to float: a = float(x)
#convert from float to int: b =
int(y)
#convert from int to complex:
c = complex(x)
print(a) print(b) print(c)
print(type(a)) print(type(b))
print(type(c))
Output
1.0
2 (1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
2 April 2022 80
Random Number
• Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9: import random
print(random.randrange(1, 10))
Output: 7
2 April 2022 81
Python Casting
Specify a Variable Type:
•There may be times when you want to specify a type on to a variable. This can be done with
casting.
Casting in python is therefore done using constructor functions:
•int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
•float()- constructs a float number from an integer literal, a
float literal or a string literal
(providing the string represents a float or an integer)
•str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals.
2 April 2022 82
Example: Integers
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
Output:
1
2
3
2 April 2022 83
Example: Floats
x = float(1) y
= float(2.8) z =
float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)
Output:
1.0
2.8
3.0
4.2
2 April 2022 84
Example: Strings
x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)
Output
s1 2
3.0
2 April 2022 85
Python Operators
• Operators are used to perform operations on variables and values.
• In the example below, we use the + operator to add together two values:
Example
• print(10 + 5)
2 April 2022 86
Python divides the operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
2 April 2022 87
Python Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
/ / Floor division x / / y
2 April 2022 88
Python Assignment Operators
• Assignment operators are used to assign values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/ = x / = 3 x = x / 3
%= x %= 3 x = x % 3
/ / = x / / = 3 x = x / / 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
| = x | = 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
2 April 2022 89
Python Comparison Operators
• Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal
to
x >= y
<= Less than or equal to x <= y
2 April 2022 90
Python Logical Operators
• Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are
true
x < 5 and x < 10
or Returns True if one of the statements
is true
x < 5 or x < 4
not Reverse the result, returns False if the
result is true
not(x < 5 and x < 10)
2 April 2022 91
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
Operator Description Example
is
Returns True if both variables are the
same object
x is y
is not
Returns True if both variables are not
the same object
x is not y
2 April 2022 92
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in
Returns True if a sequence with the specified
value is present in the object
x in y
not in
Returns True if a sequence with the specified
value is not present in the object
x not in y
2 April 2022 93
Python Bitwise Operators
• Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left
shift
Shift left by pushing zeros in from the right and let the leftmost
bits fall off
>> Signed right
shift
Shift right by pushing copies of the leftmost bit in from the left,
and let the rightmost bits fall off
2 April 2022 94
Expressions in Python
• An expression is a combination of operators and operands that is interpreted to produce some
other value.
• In any programming language, an expression is evaluated as per the precedence of its
operators.
• So that if there is more than one operator in an
expression, their precedence decides which operation will be performed first.
• We have many different types of expressions in Python.
2 April 2022 95
1. Constant Expressions
• These are the expressions that have constant values only.
Example:
# Constant Expressions x = 15 + 1.3
print(x)
Output
16.3
2 April 2022 96
2. Arithmetic Expressions
• An arithmetic expression is a combination of numeric values, operators, and
sometimes parenthesis.
• The result of this type of expression is
also a numeric value.
• The operators used in these expressions are arithmetic operators like addition,
subtraction, etc.
2 April 2022 97
Cont…
Operators Syntax Functioning
+ x + y Addition
– x – y Subtraction
* x * y Multiplication
/ x / y Division
/ / x / / y Quotient
% x % y Remainder
** x ** y Exponentiation
2 April 2022 98
Example
# Arithmetic Expressions
x = 40
y = 12
add = x + y sub = x - y
pro = x * y div = x / y
print(add)
print(sub) print(pro)
print(div)
Output
52
28
480
3.3333333333333335
2 April 2022 99
3. Integral Expressions
• These are the kind of expressions that produce only integer results after all
computations and type conversions.
# Integral Expressions a = 13
b = 12.0
c = a + int(b) print(c)
Output
25
2 April 2022 100
4. Floating Expressions
• These are the kind of expressions which produce floating point numbers as result after all
computations and type conversions.
Example:
# Floating Expressions
a = 13
b = 5
c = a / b print(c)
Output
2.6