Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit I Python Introduction

The document provides an overview of Python programming, highlighting its features such as ease of use, versatility, and extensive libraries. It discusses various applications of Python across fields like data science, web development, and artificial intelligence, as well as popular frameworks and libraries. Additionally, it explains Python's internal workings, including the compilation process and the role of the Python Virtual Machine.

Uploaded by

sakharkarsadia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit I Python Introduction

The document provides an overview of Python programming, highlighting its features such as ease of use, versatility, and extensive libraries. It discusses various applications of Python across fields like data science, web development, and artificial intelligence, as well as popular frameworks and libraries. Additionally, it explains Python's internal workings, including the compilation process and the role of the Python Virtual Machine.

Uploaded by

sakharkarsadia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Programming in

Python
(23DCE2101)
(As per NEP 2023 pattern)
Unit I

Introduction to
Python Programming
Features of Python
• Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike
traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
• Expressive Language: It allows programmers to express complex concepts in just a few
lines of code or reduces Developer's Time.
• Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
• Object-Oriented Language: It supports object-oriented programming, making writing
reusable and modular code easy.
• Open Source Language: Python is open source and free to use, distribute and modify.
• Extensible: Python can be extended with modules written in C, C++, or other languages.
• Learn Standard Library: Python's standard library contains many modules and functions
that can be used for various tasks, such as string manipulation, web programming, and
more.
Continued…

• GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and
PyQt, allowing developers to create desktop applications easily.
• Integrated: Python can easily integrate with other languages and technologies, such as C/C+
+, Java, and . NET.
• Embeddable: Python code can be embedded into other applications as a scripting language.
• Dynamic Memory Allocation: Python automatically manages memory allocation, making it
easier for developers to write complex programs without worrying about memory
management.
• Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and
frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide
range of problems.
• Versatility: Python is a universal language in various domains such as web development,
machine learning, data analysis, scientific computing, and more.
Continued…
• Large Community: Python has a vast and active community of developers contributing to
its development and offering support. This makes it easy for beginners to get help and
learn from experienced developers.
• Career Opportunities: Python is a highly popular language in the job market. Learning
Python can open up several career opportunities in data science, artificial intelligence,
web development, and more.
• High Demand: With the growing demand for automation and digital transformation, the
need for Python developers is rising. Many industries seek skilled Python developers to
help build their digital infrastructure.
• Increased Productivity: Python has a simple syntax and powerful libraries that can help
developers write code faster and more efficiently. This can increase productivity and save
time for developers and organizations.
• Big Data and Machine Learning: Python has become the go-to language for big data and
machine learning. Python has become popular among data scientists and machine
learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
Where is Python used?
• Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
• Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better languages for this
field, but it can be used with other languages for making Applications.
• Console-based Applications: Python is also commonly used to create command-line or
console-based applications because of its ease of use and support for advanced features
such as input/output redirection and piping.
• Mobile Applications: While Python is not commonly used for creating mobile applications,
it can still be combined with frameworks like Kivy or BeeWare to create cross-platform
mobile applications.
• Software Development: Python is considered one of the best software-making languages.
Python is easily compatible with both from Small Scale to Large Scale software.
Continued…

• Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language


for artificial intelligence and machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and PyTorch.
• Web Applications: Python is commonly used in web development on the backend with
frameworks like Django and Flask and on the front end with tools like JavaScript and
HTML.
• Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.
• 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
• Machine Learning: Python is widely used for machine learning due to its simplicity,
ease of use, and availability of powerful machine learning libraries.
Continued…

• Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
• Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
• Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical
computing capabilities for tasks like data analysis, machine learning, and more.
• Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
• Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
• Gaming: Python has libraries like Pygame, which provide a platform for developing games
using Python.
Continued…

• IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
• Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
• DevOps: Python is widely used in DevOps for automation and scripting of
infrastructure management, configuration management, and deployment processes.
• Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
• Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
• Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.
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.
• Frameworks:
• Web development (Server-side) - Django Flask, Pyramid, CherryPy
• GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
• Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
• Kivy: a framework for building multi-touch applications
• Pytest: a testing framework for Python
• Django REST framework: a toolkit for building RESTful APIs
• FastAPI: a modern, fast web framework for building APIs
Python Virtual Machine (PVM)
• Frozen binaries
• Run a python program in a interactive mode
• Run a python program in Script or file mode
• Python interpreter
• Python run time engine
Run Time Engine
• Software that must be running in the computer for applications to
execute. For example, all programming language interpreters are runtime
engines. They convert the program, which is in its original source code or
which has been converted into an interim, intermediate language, into
machine language. In addition, runtime engines provide common
routines and functions that the applications require.

• Although not classified as such, one might call an operating system a


runtime engine because it is always required. Indeed, it "is" the essential
runtime engine; however, the OS falls into the "runtime environment"
category.
Runtime Environment
• A configuration of hardware and software. It includes the CPU type,
operating system and any runtime engines or system software
required by a particular category of applications.
Libraries
• GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
• Machine Learning: Scikit-learn
• Mathematics - Numpy, Pandas, etc.
• BeautifulSoup: a library for web scraping and parsing HTML and XML
• Requests: a library for making HTTP requests
• SQLAlchemy: a library for working with SQL databases
• Pygame: a library for game development
• Streamlit: a library for building interactive web apps for machine learning and
data science
• NLTK: a library for natural language processing
Typical Python program
structure
#Python program structure #documentation section
import math #import statement
Documentation Section radius=5 #global declaration section
class Circle(): #class section
Import Statement def getArea(self):
Global Declaration Section return math.pi.radius*radius
def getCircumference(self):
Class Section
return radius*2*math.pi
Data Members Optional def showradius(): #sub program section
Member Function print(“Radius =“,radius)
showradius() #playground section
c=Circle()
Subprogram Section print(“Area =“,c.getArea())
print(“Circumference = “, c.getCircumference())
Play Ground Section
Essential OUTPUT:
Radius = 5
Area = 78.53981633974483
Circumference = 31.41592653589793
Python Implementations

“Traditional“ or default implementation of Python is called CPython.


• A number of alternative implementations are available as well,
namely
• IronPython (Python running on .NET)
• Jython (Python running on the Java Virtual Machine)
• PyPy (A fast python implementation with a JIT compiler)
• Stackless Python (Branch of CPython supporting microthreads)
• MicroPython (Python running on micro controllers)
Other parties have re-packaged CPython. These re-packaging often include more libraries or are
specialized for a particular application:
• ActiveState ActivePython (commercial and community versions, including scientific computing modules)
• pythonxy (Scientific-oriented Python Distribution based on Qt and Spyder)
• winpython (WinPython is a portable scientific Python distribution for Windows)
• Conceptive Python SDK (targets business, desktop and database applications)
• Enthought Canopy (a commercial distribution for scientific computing)
• PyIMSL Studio (a commercial distribution for numerical analysis – free for non-commercial use)
• Anaconda Python (a full Python distribution for data management, analysis and visualization of large
data sets)
• eGenix PyRun (a portable Python runtime, complete with stdlib, frozen into a single 3.5MB - 13MB
executable file)

If you want to host and run Python in the cloud, these implementations may be right for you:
• PythonAnywhere (freemium hosted Python installation which lets you run Python in the browser, e.g.
for tutorials, showcases, etc.)
Internal working of Python
• Python is an object-oriented programming language like Java. Python is called
an interpreted language. Python uses code modules that are interchangeable
instead of a single long list of instructions that was standard for functional
programming languages. The standard implementation of Python is called
“cpython”. It is the default and widely used implementation of Python.

• Internal working of Python:


• Python doesn’t convert its code into machine code, something that hardware
can understand. It converts it into something called byte code. So within
Python, compilation happens, but it’s just not in a machine language. It is into
byte code (.pyc or .pyo) and this byte code can’t be understood by the CPU. So
we need an interpreter called the Python virtual machine to execute the byte
codes.
How is Python Source Code Converted into
Executable Code
The Python source code goes through the following to generate an
executable code:
• Step 1:
The Python compiler reads a Python source code or instruction in the
code editor. In this first stage, the execution of the code starts.
• Step 2:
After writing Python code it is then saved as a .py file in our system. In
this, there are instructions written by a Python script for the system.
• Step 3:
In this the compilation stage comes in which source code is converted
into a byte code. Python compiler also checks the syntax error in this step
and generates a .pyc file.
• Step 4:
Byte code that is .pyc file is then sent to the Python Virtual Machine(PVM)
which is the Python interpreter. PVM converts the Python byte code into
machine-executable code and in this interpreter reads and executes the given
file line by line. If an error occurs during this interpretation then the conversion
is halted with an error message.
• Step 5:
Within the PVM the bytecode is converted into machine code that is the binary
language consisting of 0’s and 1’s. This binary language is only understandable
by the CPU of the system as it is highly optimized for the machine code.
• Step 6:
In the last step, the final execution occurs where the CPU executes the machine
code and the final desired output will come as according to your program.
How Python Internally Works?
• Code Editor:
Code Editor is the first stage of programs where we write our source code. This is
human-readable code written according to Python’s syntax rules. It is where the
execution of the program starts first.
• Source code:
The code written by a programmer in the code editor is then saved as a .py file in a
system. This file of Python is written in human-readable language that contains the
instructions for the computer.
• Compilation Stage:
The compilation stage of Python is different from any other programming language.
Rather than compiling a source code directly into machine code. python compiles a
source code into a byte code. In the compilation stage python compiler also checks
for syntax errors. after checking all the syntax errors, if no such error is found then it
generates a .pyc file that contains bytecode.
• Python Virtual Machine(PVM):
The bytecode then goes into the main part of the conversion is the Python
Virtual Machine(PVM). The PVM is the main runtime engine of Python. It is an
interpreter that reads and executes the bytecode file, line by line. Here In the
Python Virtual Machine translate the byte code into machine code which is the
binary language consisting of 0s and 1s. The machine code is highly optimized
for the machine it is running on. This binary language is only understandable by
the CPU of a system.
• Running Program:
At last, the CPU executes the given machine code and the main outcome of the
program comes as performing task and computation you scripted at the
beginning of the stage in your code editor.
Python Libraries/Modules
• When you import libraries or modules in your Python program. Firstly
python checks if the given module is built-in, and executes the
corresponding C code. If the module is not built-in then the list of
directories is defined in sys. path. the directory of the input script, and
directories listed in the PYTHONPATH. if a .py file corresponds to the
modules imported, Python creates a new module object, On
executing the code in the .py file within the object’s namespace. Then
Python compiles source code into byte code( the .pyc file), allowing
for quicker execution
Internal Working of Python
Syntax Checker and
Translator Syntax error messages
Python Code

Byte Code

User Inputs Other error messages


Python Virtual
Machine (PVM)

Program
Outputs
Basic Building Blocks of Python
• Identifiers
• Keywords
• Variables
• Indentation
• Comments
Identifiers
• A Python identifier is a name given to a function, class, variables,
module or other objects that is used in Python.
• Rules to form an identifier in Python:
1. Combination of uppercase (A-Z), lowercase letters (a-z), underscores(_), and
digits (0-9) only.
2. Identifier cannot start with a digit
3. Cannot use keywords as identifiers
4. Python is case sensitive language.
• Valid identifiers: sum, product1, Final_Sum
• Invalid identifiers: 2sum, loan%_sanctioned, data-type
Keywords
• Python keywords are reserved words that have specific meaning and
function.
• E.g. lambda, for, if, class, etc.
• Keywords are used to define the syntax and structure of the
programming language.
Variables
• A variables is a container that stores values that we can access or change.
• A variables is a name given to memory location where value can be stored that can
be used in the program.
• The size of the memory reserved by the variable depends on the type of data it is
going to hold.
• A variable, as the name indicates is something whose value is changeable over time.
• Rules to form a variable name are same that of the identifier.
• E.g. a=10
A=‘c’
sum=11.8
first_name=“Sohan”
Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Python uses indentation to indicate a block of code.
• In addition, indentation helps to increase the readability of the code.
• Generally, four white spaces are used for indentation and is preferred
over tabs.
for i in range (1,11):
print(i)
Comments
• Single line comment (#)
• Multiple line Comments:
‘’’ ……………………………….
……………………………….. ‘’’

or “”” ……………..
……………… “””
Continued…

• The Python interpreter performs following tasks to execute a Python


program:
1. The interpreter reads a Python expression or statement (source code), and
verifies that it is well formed (syntax checking). Interpreter halts translation
with an error message as soon as it encounters such an error.
2. If a Python expression is well formed, then interpreter translates it to an
equivalent form in a low level language called byte code. When the
interpreter runs a script, it completely translates it to byte code.
3. This byte code is next sent to another software component, called the
Python Virtual Machine (PVM), where it is executed. If another error
occurs during this step, execution halts with an error message.
Literals
• String Literals: “Hello”, ‘lonere’, “87601234”, ‘765.677’
• Numeric Literals: int(signed integers): 0,1,2,-1-2; long(long integers): 87676L
float(floating point): 3.14, complex(complex): 12j
• Boolean literals: True, False
• Special literals: None
• Unicode literals: u”hello”
• List literals: [], [4,6,8]
• Tuple literals: (), (8), (7,1,5)
• Dict literals: {}, {‘x’:1}
• Set literals: {2,5,9}
Continued…

• Value and type of Literals:


>>> type (‘hello python’)
<class ‘str’>
>>> type (183)
<class ‘int’>
>>>> type(74.972)
<class ‘float’>
Literal Collections
Indentation
• Most of the languages (C, C++, Java) uses braces { } to define a block of a code.
Python uses indentation.
• A code block (body of function, loop, etc.) starts with indentation and ends with
the first un-indented line. The amount of indentation is up to us, but it must be
consistent throughout that block.
• Generally, four whitespaces are used for indentation and is preferred over tabs.
• Indentation helps to convey a better structure of a program to the readers. It is
used to clarify the link between control flow constructs such as conditions or
loops, and code contained within and outside of them.
Python Data Types
• Integers (int – uses 4 bytes): -2147483648 through +2147483647
e.g. a=18
• Floating point numbers (float): It uses 64 bits and provides approximately 16 decimal
digits of precision. Python uses double-precision floating-point numbers by default,
which means that the range of float values is approximately 1.7e-308 to 1.7e+308 with
a precision of 53 bits.
e.g. x=10.1
• Complex Numbers (complex): a+bj
• Boolean (bool): True (1) and False (0)
• String data type(str): Strings are immutable (cannot be changed). Single quote or
double quote pairs can be used.
• E.g. s1=“Hello” s2=‘hi’s3=“Don’t open the door” s4=‘I said “yippee”’
Accessing the String
>>> s=“Hello Python”
>>> s[0] #get element at index 0
‘H’
>>> s[-1] #get element at last index
‘n’
>>> s[1:4] #get element from index m to n-1
‘ell’
>>> s[6:] #get element from index m to last index
‘ Python’
>>> s[:5] #get element from index 0 to n-1 index
‘Hello’
>>> s[1:12:2] #get element from m index to n-1 index with i increments
‘el yhn’
>>> s+” Programming” #Concatenate
‘Hello Python Programming’
>>> type (s) # data type of a variable s
<class ‘str’>
>>> s*3 # Repeat the string m times, here 3 times
Hello PythonHello PythonHello Python
• We can convert almost any object in Python to a string using a type constructor called str()
function
>>> S=str(42)
>>> S
‘42’
>>> type(S)
<class ‘str’>
• Split(): String to list: The split() function in a Python breaks a string into individual letters.
Use split() method to chop up a string into a list of substrings, around a specific delimiter.
The outcome of this method is a list
>>> s=“Python programming is easy”
>>> s
‘Python programming is easy’
l=s.split() # split without any argument
>>> l
[‘Python’, ‘programming’, ‘is’, ’easy’]
>>> s=“Python,programming,is,easy”
>>> s
‘Python,programming,is,easy’
>>> l=s.split(‘,’) # split() with a argument
>>> l
[‘Python’, ‘programming’, ‘is’, ’easy’]
>>> type(l)
<class ‘list’>
• join(): join list back into a string. Use this method to join the list back into a string,
with a specified delimiter in between. The outcome of join() method is a string.
>>> l
[‘Python’, ‘programming’, ‘is’, ‘easy’]
>>> type(l)
<class ‘list’>
>>> s = ‘ ‘.join(l)
>>> s
‘Python programming is easy’
>>> s=‘.’.join(l)
>>> s
‘Python.programming.is.easy’
>>> type (s)
<class ‘str’>
String built-in methods
Sr.No. String operation Explanation Example
1 + Adds two strings together x=“hello”+”world” #concatenate
2 * Replicates a string x=“ y“*5 #repeat y 5 times
3 upper converts a string to upper case x.upper()
4 lower converts a string to lower case x.lower()
5 title Capitalizes the first letter of each word x.title()
in a string
6 find, index Searches the string for a specified value >>> txt = "Hello, welcome to my world."
and returns the position of where it was >>> x = txt.find("welcome")
found >>> print(x)
7
7 rfind, rindex Searches the string for a specified value >>> txt = "Mi casa, tu casa."
and returns the last position of where it >>> x = txt.rfind("casa")
was found >>> print(x)
12
Sr.No. String operation Explanation Example
8 startswith, Returns true if the string starts/ends >>> txt = "Hello, welcome to my world."
endswith with the specified value >>> x = txt.startswith("Hello")
>>> print(x)
True
9 replace Returns a string where a specified value >>> txt = "I like bananas"
is replaced with a specified value >>> x = txt.replace("bananas", "apples")
(Replaces a target with a new string) >>> print(x)
I like apples
10 strip, rstrip, Returns a trimmed version of the string. >>> txt = " banana "
lstrip Returns a right trim version of the string >>> x = txt.lstrip()
Returns a left trim version of the string >>> print("of all fruits", x, "is my
favourite")
of all fruits banana is my favourite
11 encode Returns an encoded version of the >>> txt = "My name is Ståle"
string. >>> x = txt.encode()
Default encoding is UTF-8. >>> print(x)
b'My name is St\xc3\xe5le'
Difference Between index() vs
find()
index() find()
Returns an exception if substring isn’t
found Returns -1 if substring isn’t found

It is the correct function to use when


It shouldn’t be used if you are not sure you are not sure about the presence of a
about the presence of the substring substring
This can be applied to strings, lists and
tuples This can only be applied to strings

It can be used with conditional


It cannot be used with conditional statement to execute a statement if a
statement substring is found as well if it is not
Input and Output in Python
• In python, input() function is used to accept an input from a user. #Older version –
raw_input()
• Syntax: variable_name=input() #without any argument
variable_name=input(‘String’) #with argument
>>> input()
Hello Python
‘Hello Python’
>>> x = input(“Enter data: ”)
Enter data: 123.76
>>> print(x)
‘123.76’
• Syntax: print(expression/constant/variable)
>>> print(‘Hello’)
Hello
>>> a=‘Hello’
>>> b=“Python”
>>> print(a+b)
HelloPython
Arithmetic operators
Sr. Operator Operator Name Description Example
No. Symbol (a=10, b=20)
1 + Addition Adds the value of the left and right operands >>> a + b
30
2 - Subtraction Subtracts the value of the right operand from the >>> b - a
value of the left operand 10
3 * Multiplication Multiply the values of left and right operands >>> a * b
200
4 / Divide Divides the value of the left operand by the value >>> a / b
of right operand 2.0
5 ** Exponent Performs exponential calculation, raises first >>> a ** 2
operand to the second operand 1000
6 % Modulus Returns the remainder after dividing the left >>> a % b
operand by the right operand 10
7 // Floor division Division of operands where the solution is a >>> b // a
quotient left after removing decimal numbers 2
Assignment Operators (Augmented
assignment operators)
Sr. No. Operator Description Example
1 = Assigns values from right side operands to left side operand c=a+b assigns value of
a+b into c
2 += It adds right operand to the left operand and assign the c+=a equals to c=c+a
result to the left operand
3 -= It subtracts right operand from the left operand and assign c-=a equals to c=c-a
the result to the left operand
4 *= It multiply right operand with the left operand and assign c*=a equals to c=c*a
the result to the left operand
5 /= It divide left operand by the right operand and assign the c/=a equals to c= c/a
result to the left operand
6 %= Its takes modulus using two operands and assigns result to c%=a equals to c=c%a
the left operand
7 **= Performs exponential (power) calculation on operators and c**=a equals to c=c**a
assign result to left operand
8 //= Performs floor division operation on two operands and c//=a equals to c=c//a
assign result to the left operand
Relational or comparison operators
Sr. Operator Description Example (Result is always True or False)
No. a=10, b=20, c=20
1 == Equality operator >>> a == b
False
>>> b == c
True
2 != Not equality operator >>> a != b
True
>>> b != c
Fasle
3 > Greater than operator >>> a > b
False
>>> b > c
False
>>> b > a
True
Sr. No. Operator Description Example (Result is always True or
False)
a=10, b=20, c=20
4 < Less than operator >>> a < b
True
>>> b < a
False
5 >= Greater than or equal to >>> b >= c
True
>>> a >= b
False
6 <= Less than or equal to >>> a <= b
False
>>> c <= b
True
Logical Operator
Sr. No. Operator Description Example
a is True and b is False, c=8 and d=10
1 and If both operands are true then result >> a and b
(Logical is true False
AND) >>> c < d and c!=d
True
2 or If any of two operands are non-zero, >>> a or b
(Logical condition is true True
OR) >>> a == b or c < d
True
3 not Used to reverse the logical state of >>> not (a and b)
(Logical its operand True
NOT) >>> not(c > d)
True
Bitwise operators
Sr. Operator Description Example
No. e.g. a=10 and b=4
i.e. 0b1010 and 0b0100

1 & This operator performs AND operation between a & b = 1010 & 0100 = 0
(Bitwise AND) operands. Operator copies a bit, to the result, if it >>> a & b
exists in both operands 0
>>> bin (a & b)
‘0b0’
2 | It copies a bit, to the result, if it exists in either (or a | b = 1010 | 0100 = 14
(Bitwise OR) both) operands (1110)
3 ^ It copies a bit, to the result, if it exists in only on a ^ b = 1010 ^ 0100 = 14
(Bitwise XOR) operand but not both (1110)
4 ~ It is unary operator and it has the effect of flipping ~ a = ~ 1010 = 0101
(Bitwise one’s the bit i.e. opposite the bit of the operand
complement)

5 << The left operands value is moved left by the number a << 2 = 1010 << 2
(Bitwise left shift) of bits specified by the right operand = 101000 = 40
6 >> The left operands value is moved right by the a >> 2 = 1010 >> 2
(Bitwise right shift) number of bits specified by the right operand = 0010 = 2
Bitwise operators
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
• Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left (fills 1 in the case of
a negative number) as a result. Similar effect as of dividing the number with some power of two.
Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
• Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar
effect as of multiplying the number with some power of two.
Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
Identity Operators
• Sometimes, need to compare the memory address of two objects. 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
• Used to check whether both operands are same or not. They are used to check if
the two values are located on the same part of the memory. Two variables that
are equal does not imply that they are identical.
is Return True, if variables on either side of the operator >>> a=3
point to the same object and False otherwise >>> b=3
>>> print (a is b)
True
is not Return False, if variables on either side of the operator >>> a=3
point to the same object and True otherwise >>> b=3
>>> print (a is not b)
False
Continued…
num1 = 10
num2 = 10
result = num1 is num2
print(result)

# Output:
True
• Although the values of num1 and num2 are the same, Python
optimizes small integer objects to share the same memory location,
leading to a True output.
id() function
• Using id() Function with Variables:
python code

x=5
y=x
print(id(x)) # Output: 140732337151648
print(id(y)) # Output: 140732337151648
In this example, both x and y reference the same memory location, as
indicated by their identical id() value
Membership Operators
• These are used to find the existence of a particular element in the sequence and used only with
sequences like string, tuple, list, dictionary, etc.

Sr. No. Operator Description Example


1 in True if value is found in list or in sequence, and false >>> x=‘Hello world’
otherwise >>> print (‘H’ in x)
True
2 not in True if value is not found in list or in sequence, and >>> x=‘Hello world’
false otherwise >>> print (‘H’ not in x)
False

• >>> print (‘Hello’ not in x) >>> print (1 in y)


False True
>>> y = {1:’a’, 2:’b’, ‘c’:3} >>> print (‘c’ in y)
True
>>> print (3 in y) # search is for key only,
False # and not for value
Is There a Difference Between
== and is?
• Indeed, there is a crucial difference between the equality operator (==) and the identity operator
(is) in Python:
== checks if two objects have the same values.
is checks if two objects reference the same memory location.
• Example: Difference between == and is
• Python code

a = [1, 2, 3]
b = [1, 2, 3]
result1 = a == b # Output: True (values are the same)
result2 = a is b # Output: False (memory locations are different)
• In this example, result1 is True because the values of a and b are the same. However, result2 is
False because the memory locations of a and b are different. This distinction is vital when
comparing objects in Python.
Python Operator Precedence and Associativity
Precedence Operators Description Associativity
1 () Parentheses Left to right

2 x[index], x[index:index] Subscription, slicing Left to right

Await expression (used in


3 await x concurrent programming) N/A

4 ** Exponentiation Right to left

5 +x, -x, ~x Positive, negative, bitwise NOT Right to left

Multiplication, matrix, division, floor


6 *, @, /, //, % division, remainder Left to right

7 +, - Addition and subtraction Left to right

8 <<, >> Shifts Left to right


9 & Bitwise AND Left to right

10 ^ Bitwise XOR Left to right

11 | Bitwise OR Left to right

Comparisons,
in, not in, is, is
12 membership tests, Left to Right
not, <, <=, >, >=, !=, ==
identity tests

13 not x Boolean NOT Right to left

14 and Boolean AND Left to right

15 or Boolean OR Left to right

16 if-else Conditional expression Right to left

17 lambda Lambda expression N/A

Assignment expression
18 := (walrus operator) Right to left
Small Python Programs
1. Program to find the square root of a number
2. Program to find the area of Rectangle
3. Program to calculate area and perimeter of the square
4. Program to calculate the surface volume and area of a cylinder
5. Program to swap the value of two variables
End of Unit I – Introduction to Python
Programming

You might also like