Python Programming.1st Semester

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Python Programming

Unit - 1
1.1 The Essence of Computational Problem Solving in Python
'Computational problem solving' is the iterative process of developing
computational solutions to problems. Computational solutions are expressed as
logical sequences of steps (i.e. algorithms), where each step is precisely defined so
that it can be expressed in a form that can be executed by a computer.
In order to solve a problem computationally, two things are needed:
● A representation that captures all the relevant aspects of the problem.
● An algorithm that solves the problem by use of the representation.

1.2 Limits of Computational Problem Solving


Any algorithm that correctly solves a given problem must solve the problem
in a reasonable amount of time; otherwise it is of limited practical use.

1.3 Computer Algorithms

What Is an Algorithm?
An algorithm is a set of commands that must be followed for a computer to
perform calculations or other problem-solving operations. According to its formal
definition, an algorithm is a finite set of instructions carried out in a specific order
to perform a particular task.
An algorithm is a finite number of clearly described, unambiguous “doable”
steps that can be systematically followed to produce a desired result for given input
in a finite amount of time.
Algorithms and Computers: A Perfect Match

Because computers can execute instructions very quickly and reliably


without error, algorithms and computers are a perfect match.
What is the need for algorithms?
 Algorithms are necessary for solving complex problems efficiently and
effectively.
 They help to automate processes and make them more reliable, faster, and
easier to perform.
 Algorithms also enable computers to perform tasks that would be difficult or
impossible for humans to do manually.
 They are used in various fields such as mathematics, computer science,
engineering, finance, and many others to optimize processes, analyze data,
make predictions, and provide solutions to problems.
Characteristics of an Algorithm
Properties of Algorithm:
 It should terminate after a finite time.
 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the same input
case.
 Every step in the algorithm must be effective i.e. every step should do some
work.

1.4 Computer Hardware

Computer Parts or Components

Computer components are the essential building parts of developing a


functional computer system. The components that make up a computer are called
computer components. The processor (CPU), memory, and input/output devices
are every computer's three main building blocks. Initially computers were
primarily used for numerical computations because any information can be
numerically encoded. The ability of computers to interpret information for several
purposes was quickly recognized.

There are 5 main computer components that are given below:

 Input Devices

 CPU

 Output Devices

 Primary Memory

 Secondary Memory
Input Devices

Input device enables the user to send data, information, or control signals to a
computer. The Central Processing Unit (CPU) of a computer receives the input and
processes it to produce the output.

Some of the popular input devices are:

Keyboard, Mouse, Scanner, Joystick, Light Pen, Digitizer, Microphone,


Magnetic Ink Character, Recognition (MICR), Optical Character Reader (OCR),
Digital Camera, Touch Pad, Remote, Touch screen, VR, Webcam, Biometric
Devices.

Keyboard

The keyboard is a basic input device that is used to enter data into a computer or
any other electronic device by pressing keys. It has different sets of keys for letters,
numbers, characters, and functions. Keyboards are connected to a computer
through USB or a Bluetooth device for wireless communication.
Types of Keys

 Numeric Keys: It is used to enter numeric data or move the cursor. It


usually consists of a set of 17 keys.
 Typing Keys: The letter keys (A-Z) and number keys (09) are among these
keys.
 Control Keys: These keys control the pointer and the screen. There are four
directional arrow keys on it. Home, End, Insert, Alternate(Alt), Delete,
Control(Ctrl), etc., and Escape are all control keys (Esc).
 Special Keys: Enter, Shift, Caps Lock, NumLk, Tab, etc., and Print Screen
are among the special function keys on the keyboard.
 Function Keys: The 12 keys from F1 to F12 are on the topmost row of the
keyboard.

Mouse

The most common pointing device is the mouse. The mouse is used to move a
little cursor across the screen while clicking and dragging. The cursor will stop
if you let go of the mouse. The computer is dependent on you to move the
mouse; it won’t move by itself. As a result, it’s an input device.

A mouse is an input device that lets you move the mouse on a flat surface to
control the coordinates and movement of the on-screen cursor/pointer.

The left mouse button can be used to select or move items, while the right
mouse button when clicked displays extra menus.
Joystick
A joystick is a pointing device that is used to move the cursor on a computer
screen. A spherical ball is attached to both the bottom and top ends of the stick.
In a socket, the lower spherical ball slides. You can move the joystick in all four
directions.

Track Ball
Track Ball is an accessory for notebooks and laptops, which works on behalf of a
mouse. It has a similar structure to a mouse. Its structure is like a half-inserted
ball and we use fingers for cursor movement. Different shapes are used for this
like balls, buttons, or squares.

Light Pen
A light pen is a type of pointing device that looks like a pen. It can be used to
select a menu item or to draw on the monitor screen. A photocell and an optical
system are enclosed in a tiny tube. When the tip of a light pen is moved across a
monitor screen while the pen button is pushed, the photocell sensor element
identifies the screen location and provides a signal to the CPU.

Web Camera
Because a web camera records a video image of the scene in front of it, a webcam
is an input device. It is either built inside the computer (for example, a laptop) or
attached through a USB connection. A webcam is a computer-connected tiny
digital video camera. It’s also known as a web camera because it can take images
and record video. These cameras come with software that must be installed on the
computer in order to broadcast video in real-time over the Internet. It can shoot
images and HD videos, however, the video quality isn’t as good as other cameras
(In Mobiles or other devices or normal cameras).

Output Devices
Output Devices are the devices that show us the result after giving the input to a
computer system. Output can be of many different forms like image, graphic
audio, video, etc. Some of the output devices are described below.

I. Monitor
Monitors, also known as Visual Display Units (VDUs), are a computer’s primary
output device. It creates images by arranging small dots, known as pixels, in a
rectangular pattern. The amount of pixels determines the image’s sharpness.
The two kinds of viewing screens used for monitors are described below.

Cathode-Ray Tube (CRT) Monitor: Pixels are minuscule visual elements that
make up a CRT display. The higher the image quality or resolution, the smaller
the pixels.
Flat-Panel Display Monitor: In comparison to the CRT, a flat-panel display is a
type of video display with less volume, weight, and power consumption. They
can be hung on the wall or worn on the wrist.
Flat-panel displays are currently used in calculators, video games, monitors,
laptop computers, and graphical displays.

II. Printer
Printers are output devices that allow you to print information on paper. There are
certain types of printers which are described below.

 Impact Printers
 Character Printers
 Line Printers
 Non-Impact Printers
 Laser Printers
 Inkjet Printers
Impact Printer
Characters are printed on the ribbon, which is subsequently crushed against the
paper, in impact printers. The following are the characteristics of impact printers:

 Exceptionally low consumable cost.


 Quite noisy
 Because of its low cost, it is ideal for large-scale printing.
 To create an image, there is physical contact with the paper.

Character Printers
Character Printer has the capability to print only one character at a time. It is of
two types.

 Dot Matrix Printer


 Daisy Wheel

Line Printers
Line Printers are printers that have the capability to print one line at a time. It is
of two types.
 Drum Printer
 Chain Printer

Non-Impact Printers
Characters are printed without the need for a ribbon in non-impact printers.
Because these printers print a full page at a time, they’re also known as Page
Printers. The following are the characteristics of non-impact printers:
 Faster
 They don’t make a lot of noise.
 Excellent quality
 Supports a variety of typefaces and character sizes

Laser Printers
Laser Printers use laser lights for producing dots which will produce characters
on the page.

Inkjet Printers
Inkjet printers are printers that use spray technology for printing papers. High-
quality papers are produced in an Inkjet printer. They also do color printing.

III. Speakers
Speakers are devices that produce sound after getting a command from a
computer. Nowadays, speakers come with wireless technology also like
Bluetooth speakers.

IV. Projector
Projectors are optical devices that have the work to show visuals on both types of
screens, stationary and moving both. It helps in displaying images on a big
screen. Projectors are generally used in theatres, auditoriums, etc.

V. Plotter
Plotter is a device that helps in making graphics or other images to give a real
view. A graphic card is mandatorily required to use these devices. These are the
pen-like devices that help in generating exact designs on the computer.

VI. Headphones
Headphones are just like a speaker, which is generally used by a single person or
it is a single-person usable device and is not commonly used in large areas. These
are also called headsets having a lower sound frequency.

Binary representation

All information within a computer system is represented using only two


digits, 0 and 1, called binary representation.

The Binary Number System

The term bit stands for binary digit. A byte is a group of bits operated on
as a single unit in a computer system, usually consisting of eight bits.

Operating Systems—Bridging Software and Hardware

An operating system is software that has the job of managing the hardware
resources of a given computer and providing a particular user interface.

Central Processing Unit (CPU)

A Central Processing Unit is also called a processor, central processor, or


microprocessor. It carries out all the important functions of a computer. It receives
instructions from both the hardware and active software and produces output
accordingly. It then performs calculations, manipulates data, and produces output
based on those instructions. It stores all important programs.

Components of CPU

1.5 Computer Software


Computer software is a set of program instructions, including related data
and documentation, which can be executed by computer.

Syntax, Semantics, and Program Translation:

● The syntax of a language is a set of characters and the acceptable


sequences of those characters.
● The semantics of a language is the meaning associated with each
syntactically correct sequence of characters.
● A compiler is a translator program that translates programs directly
into machine code to be executed by the CPU.
● An interpreter executes program instructions in place of (“running on
top of”) the CPU. Syntax errors are caused by invalid syntax.
Semantic (logic) errors are caused by errors in program logic.
Procedural vs .Object-Oriented Programming

● Python supports both procedural and object-oriented programming.


● Procedural programming and object-oriented programming are two major
programming paradigms in use today.
Types of Software
1. System Software
 Operating System
 Language Processor
 Device Driver
2. Application Software
 General Purpose Software
 Customize Software
 Utility Software

1.6 THE PROCESS OF COMPUTATIONAL PROBLEM SOLVING


1.7 PYTHON PROGRAMMING LANGUAGE
Programming Language
A programming language is a set of instructions and syntax used to create software
programs. Some of the key features of programming languages include:

● Syntax: The specific rules and structure used to write code in a


programming language.
● Data Types: The type of values that can be stored in a program, such as
numbers, strings, and booleans.
● Variables: Named memory locations that can store values.
● Operators: Symbols used to perform operations on values, such as addition,
subtraction, and comparison.
● Control Structures: Statements used to control the flow of a program, such
as if-else statements, loops, and function calls.
● Libraries and Frameworks: Collections of pre-written code that can be
used to perform common tasks and speed up development.
● Paradigms: The programming style or philosophy used in the language,
such as procedural, object-oriented, or functional.
Examples of popular programming languages include Python, Java, C++,
JavaScript, and Ruby.

Characteristics of a programming Language –

● A programming language must be simple, easy to learn and use, have good
readability, and be human recognizable.
● Abstraction is a must-have characteristic for a programming language in
which the ability to define the complex structure and then its degree of
usability comes.
● A portable programming language is always preferred.
● Programming language’s efficiency must be high so that it can be easily
converted into machine code and its execution consumes little space in
memory.
● A programming language should be well structured and documented so that
it is suitable for application development.
● Necessary tools for the development, debugging, testing, maintenance of a
program must be provided by a programming language.
● A programming language should provide a single environment known as
Integrated Development Environment(IDE).
● A programming language must be consistent in terms of syntax and
semantics.

Introduction to 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.
Features of Python:
1. Simple
Python is a simple and minimalistic language. Reading a good Python program
feelsalmost like reading English language.
2. Easy to learn
Python uses very few keywords. Python has an extraordinarily simple syntax and
simple program structure.
3. Open Source
There is no need to pay for Python software. Python is FLOSS (Free/Library and
Open Source Software). Its source can be read, modified and used in programs as
desired by the programmers.
4. High level language

When you write programs in Python, you never need to bother aboutthe low- level
details such as managing the memory used by your program, etc.

5. Dynamically typed
Python provides IntelliSense. IntelliSense to make writing your code easier and
more error-free. IntelliSense option includes statement completion, which provides
quick access to valid member function or variables, including global, via the
member list. Selecting from the list inserts the member into your code.

6. Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make it
work on) many platforms. All your Python programs can work on any of these
platforms without requiring any changes at all if you are careful enough to avoid
any system-dependent features.
7. Platform independent
When a Python program is compiled using a Python compiler, it generates byte
code. Python’s byte code represents a fixed set of instructions that run on all
operating systems and hardware. Using a Python Virtual Machine (PVM), anybody
can run these byte code instructions on any computer system. Hence, Python
programs are not dependent on any specific operating system.
8. Procedure and Object Oriented
Python supports procedure-oriented programming as well as object-oriented
programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In
object- oriented languages, the program is built around objects which combine data
and functionality.

History of python
● Guido van Rossum is the creator of the Python programming language
released in the early 1990s.
● Its name comes from a 1970s British comedy television show called Monty
Python’s Flying Circus.
● Open sourced from the beginning.
FLAVORS OF PYTHON
A flavor of Python simply refers to the different Python compilers. These flavors
are useful to integrate various programming languages into Python. Let us look at
some of these flavors:
C Python, J Python, PyPy, Ruby Python, Python xy, Anaconda Python,
Stockless Python.
Applications of python
● Web and Internet Development
● GUI
● Software Development
● AI and Machine Learning
● Database access
● Network Programming
● Games and 3D Graphics
Who uses python today?

Installing of python
● Python is well supported and freely available at
https://www.python.org/downloads/
● Latest version : 3.8.5

Python IDLE
● An Integrated Development Environment (IDLE) is a bundled set of
software tools for
● Program development.
● An editor for creating and modifying programs
● A translator for executing programs
● A program debugger provides a means of taking control of the execution of
a program
● to aid in finding program errors
The Python Standard Library is a collection of modules, each providing specific
functionality, beyond what is included in the core part of Python.
Python character set
Letters: Upper case and lower case letters
Digits: 0,1,2,3,4,5,6,7,8,9
Special Symbols: Underscore (_), (,), [,], {,}, +, -, *, &, ^, %, $, #, !, Single
quote(‘),
Double quotes(“), Back slash(\), Colon(:), and Semi Colon (;)
White Spaces: (‘\t\n\x0b\x0c\r’), Space, Tab.
Token
A program in Python contains a sequence of instructions.
Python breaks each statement into a sequence of lexical components known as
tokens.
1.8 Literals in Python
A literal in Python is a syntax that is used to completely express a fixed value of a
specific data type. Literals are constants that are self-explanatory and don’t need to
be computed or evaluated. They are used to provide variable values or to directly
utilize them in expressions.
They can also be defined as raw values or data given in variables or constants.
Types of Literals in Python
 String literals
 Character literal
 Numeric literals
 Boolean literals
 List literal
 Tuple literals
 Dictionary literals
1. String Literals
A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes.
Example:
# in single quote Output:
s = 'geekforgeeks' geekforgeeks
# in double quotes geekforgeeks
t = "geekforgeeks" geek
# multi-line String for
m = '''geek geeks
for
geeks'''
print(s)
print(t)
print(m)

2. Character literal
It is also a type of Python string literal where a single character is surrounded
by single or double quotes.
# character literal in single quote Output:
v = 'n' n
# character literal in double quotes a
w = "a"
print(v)
print(w)

3. Numeric literal
They are immutable and there are three types of numeric literal:
Integer
Both positive and negative numbers including 0. There should not be any
fractional part. In this example, We assigned integer literals (0b10100, 50,
0o320, 0x12b) into different variables.
Float
These are real numbers having both integer and fractional parts. In this
example, 24.8 and 45.0 are floating-point literals because both 24.8 and 45.0 are
floating-point numbers.
Complex
The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is
the complex part. Numeric literal [ Complex ]
x = 0b10100 #Binary Literals Output:
y = 100 #Decimal Literal 20 100 141 301
z = 0o215 #Octal Literal 100.5 150.0
u = 0x12d #Hexadecimal Literal (5+3.14j) 3.14 5.0

#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)

4. Boolean literal
There are only two Boolean literals in Python. They are true and false.
5. List Literal
List object in Python is a collection of objects of other data type. List is an
ordered collection of items not necessarily of same type. Individual object in the
collection is accessed by index starting with zero.
L1=[1,"Ravi",75.50, True] Output:
print (L1, type(L1)) [1, 'Ravi', 75.5, True] <class 'list'>

6. Tuple Literal
Tuple object in Python is a collection of objects of other data type. Tuple is an
ordered collection of items not necessarily of same type.
T1=(1,"Ravi",75.50, True) Output:
print (T1, type(T1)) [1, 'Ravi', 75.5, True] <class tuple>

1.9 Variables
A variable is “a name that is assigned to a value.”
The assignment operator, = , is used to assign values to variables.
An immutable value is a value that cannot be changed.
>>>num=10 O/P : 10
>>> k=num
>>> print(k)
In Python the same variable can be associated with values of different type during
program execution.
var = 12 integer
var = 12.45 float
var = 'Hello' string

1.10 Identifier Naming


Identifiers are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given underneath.
o The variable's first character must be an underscore or alphabet (_).
o Every one of the characters with the exception of the main person might be a
letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the
identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in the
language.
o Names of identifiers are case-sensitive; for instance, my name, and MyName
isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
o Python doesn't tie us to pronounce a variable prior to involving it in the
application. It permits us to make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is
declared automatically whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.
Escape Sequences in Python
 Control characters are nonprinting characters used to control the display of
output.
 Represented by a combination of characters called an escape sequence.
 An escape sequence is a string of one or more characters used to denote
control characters.
 To print the special characters in the screen, we use the escape sequence.
 The backslash (\) serves as the escape character in Python.
Python Keywords
Keywords in Python are reserved words that can not be used as a variable name,
function name, or any other identifier.
alse await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

# Python program to demonstrate the Output:


application of iskeyword() The set of keywords in this
# importing keyword library which has version is :
lists ['False', 'None', 'True', 'and', 'as',
import keyword 'assert', 'async', 'await', 'break',
print("The set of keywords in this version 'class', 'continue', 'def', 'del', 'elif',
is: ") 'else', 'except', 'finally', 'for',
print( keyword.kwlist ) 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while',
'with', 'yield']

1.11 Python Operators


Python operators are special symbols used to perform specific operations on
one or more operands. The variables, values, or expressions can be used as
operands. For example, Python's addition operator (+) is used to perform addition
operations on two variables, values, or expressions.

The following are some of the terms related to Python operators:


 Unary operators: Python operators that require one operand to perform a
specific operation are known as unary operators.
 Binary operators: Python operators that require two operands to perform a
specific operation are known as binary operators.
 Operands: Variables, values, or expressions that are used with the operator
Types of Python Operators
 Python operators are categorized in the following categories −to perform a
specific operation.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
i. Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations
such as addition, subtraction, multiplication, etc.
The following table contains all arithmetic operators with their symbols, names,
and examples (assume that the values of a and b are 10 and 20, respectively) −

Operator Name Example

+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4

Example:
a = 21 Output:
b = 10
a: 21 b: 10 a+b: 31
c=0
c=a+b a: 21 b: 10 a-b: 11
print ("a: {} b: {} a+b: {}".format(a,b,c))
a: 21 b: 10 a*b: 210
c=a-b a: 21 b: 10 a/b: 2.1
print ("a: {} b: {} a-b: {}".format(a,b,c) )
a: 21 b: 10 a%b: 1
c=a*b
print ("a: {} b: {} a*b: {}".format(a,b,c)) a: 2 b: 3 a**b: 8
c=a/b
a: 10 b: 5 a//b: 2
print ("a: {} b: {} a/b: {}".format(a,b,c))
c=a%b
print ("a: {} b: {} a%b: {}".format(a,b,c))
a=2
b=3
c = a**b
print ("a: {} b: {} a**b: {}".format(a,b,c))
a = 10
b=5
c = a//b
print ("a: {} b: {} a//b: {}".format(a,b,c))

ii. Comparison Operators


Python Comparison operators compare the values on either side of them and
decide the relation among them. They are also called Relational operators.

The following table contains all comparison operators with their symbols, names,
and examples (assume that the values of a and b are 10 and 20, respectively) –

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.

> Greater than (a > b) is not true.

< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.

<= Less than or equal to (a <= b) is true.

Example:
a = 21 Output:
b = 10 Line 1 - a is not equal to b
if ( a == b ): Line 2 - a is not equal to b
print ("Line 1 - a is equal to b") Line 3 - a is not less than b
else: Line 4 - a is greater than b
print ("Line 1 - a is not equal to b") Line 5 - a is either less
than or equal to b
if ( a != b ): Line 6 - b is either greater
print ("Line 2 - a is not equal to b") than or equal to b
else:
print ("Line 2 - a is equal to b")

if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")

if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")

a,b=b,a #values of a and b swapped. a becomes 10, b


becomes 21
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")

if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to
b")

iii. Assignment Operators


Python Assignment operators are used to assign values to variables. Following is a
table which shows all Python assignment operators.

The following table contains all assignment operators with their symbols, names,
and examples –
Operator Example Same As

= a = 10 a = 10

+= a += 30 a = a + 30

-= a -= 15 a = a - 15

*= a *= 10 a = a * 10

/= a /= 5 a=a/5

%= a %= 5 a=a%5

**= a **= 4 a = a ** 4

//= a //= 5 a = a // 5

&= a &= 5 a=a&5

|= a |= 5 a=a|5

^= a ^= 5 a=a^5

>>= a >>= 5 a = a >> 5

<<= a <<= 5 a = a << 5


Example:
a = 21 a: 21 b: 10 c : 0
b = 10 a: 21 c = a + b: 31
c=0 a: 21 c += a: 52
print ("a: {} b: {} c : {}".format(a,b,c)) a: 21 c *= a: 1092
c=a+b a: 21 c /= a : 52.0
print ("a: {} c = a + b: {}".format(a,c)) a: 21 b: 10 c : 2
a: 21 c %= a: 2
c += a a: 21 c **= a: 2097152
print ("a: {} c += a: {}".format(a,c)) a: 21 c //= a: 99864
c *= a
print ("a: {} c *= a: {}".format(a,c))

c /= a
print ("a: {} c /= a : {}".format(a,c))

c =2
print ("a: {} b: {} c : {}".format(a,b,c))
c %= a
print ("a: {} c %= a: {}".format(a,c))

c **= a
print ("a: {} c **= a: {}".format(a,c))

c //= a
print ("a: {} c //= a: {}".format(a,c))

iv. Bitwise Operators


Python Bitwise operator works on bits and performs bit by bit operation. These
operators are used to compare binary numbers.

The following table contains all bitwise operators with their symbols, names, and
examples –

Operator Name Example

& AND a&b


| OR a|b

^ XOR a^b

~ NOT ~a

<< Zero fill left shift a << 3

>> Signed right shift a >> 3

Example:
a = 20 Output:
b = 10 a= 20 : 0b10100 b= 10 :
print ('a=',a,':',bin(a),'b=',b,':',bin(b)) 0b1010
c=0 result of AND is 0 : 0b0
c = a & b; result of OR is 30 :
print ("result of AND is ", c,':',bin(c)) 0b11110
c = a | b; result of EXOR is 30 :
print ("result of OR is ", c,':',bin(c)) 0b11110
c = a ^ b; result of COMPLEMENT is
print ("result of EXOR is ", c,':',bin(c)) -21 : -0b10101
c = ~a; result of LEFT SHIFT is 80
print ("result of COMPLEMENT is ", c,':',bin(c)) : 0b1010000
c = a << 2; result of RIGHT SHIFT is
print ("result of LEFT SHIFT is ", c,':',bin(c)) 5 : 0b101
c = a >> 2;
print ("result of RIGHT SHIFT is ", c,':',bin(c))

v. Logical Operators
Python logical operators are used to combile two or more conditions and check the
final result. There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then

The following table contains all logical operators with their symbols, names, and
examples –

Operator Name Example

and AND a and b

or OR a or b

not NOT not(a)


Example:
var = 5 Output:
print(var > 3 and var < 10) True
print(var > 3 or var < 4) True
print(not (var > 3 and var < 10)) False

vi. Membership Operators


Python's membership operators test for membership in a sequence, such as strings,
lists, or tuples.

There are two membership operators as explained below –

Operator Description Example

Returns True if it finds a variable in the specified sequence,


in a in b
false otherwise.

returns True if it does not finds a variable in the specified


not in a not in b
sequence and false otherwise.
Example:
a = 10 Output:
b = 20 a: 10 b: 20 list: [1, 2, 3, 4, 5]
list = [1, 2, 3, 4, 5 ] a is not present in the given list
print ("a:", a, "b:", b, "list:", list) b is not present in the given list
if ( a in list ): c: 2.0 list: [1, 2, 3, 4, 5]
print ("a is present in the given list") c is available in the given list
else:
print ("a is not present in the given list")
if ( b not in list ):
print ("b is not present in the given list")
else:
print ("b is present in the given list")
c=b/a
print ("c:", c, "list:", list)
if ( c in list ):
print ("c is available in the given list")
else:
print ("c is not available in the given list")
Identity Operators
Python identity operators compare the memory locations of two objects.

There are two Identity operators explained below –

vii. Identity Operators


Python identity operators compare the memory locations of two objects.
There are two Identity operators explained below −

Operator Description Example

Returns True if both variables are the same object and false
is a is b
otherwise.

Returns True if both variables are not the same object and
is not a is not b
false otherwise.

Example:
a = [1, 2, 3, 4, 5] Output:
b = [1, 2, 3, 4, 5] True
c=a False
print(a is c) False
print(a is b) True
print(a is not c)
print(a is not b)

Python Operators Precedence


Operators have different levels of precedence, which determine the order in
which they are evaluated. When multiple operators are present in an expression,
the ones with higher precedence are evaluated first.
Sr.No
. Operator & Description

1 (),[], {} Parentheses and braces


2 [index], [index:index] Subscription, slicing,
3 await x Await expression
4 ** Exponentiation
5 +x, -x, ~x Positive, negative, bitwise NOT

6
*, @, /, //, %
Multiplication, matrix multiplication, division, floor division, remainder
7 +, - Addition and subtraction
8 <<, >> Left Shifts, Right Shifts
9 & Bitwise AND
10 ^ Bitwise XOR
11 | Bitwise OR

12
in, not in, is, is not, <, <=, >, >=, !=, ==
Comparisons, including membership tests and identity tests
13 not x Boolean NOT
14 and Boolean AND
15 or Boolean OR
16 if – else Conditional expression
17 lambda Lambda expression
18 := Walrus operator

You might also like