0% found this document useful (0 votes)
2 views97 pages

MITS Python Operators Expressions Final

The document provides an introduction to Python programming, covering topics such as installation, data types, variables, and basic programming concepts. It explains Python's features, including its interpreted nature, object-oriented design, and extensive libraries. Additionally, it includes examples of Python code, variable rules, and input/output methods.

Uploaded by

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

MITS Python Operators Expressions Final

The document provides an introduction to Python programming, covering topics such as installation, data types, variables, and basic programming concepts. It explains Python's features, including its interpreted nature, object-oriented design, and extensive libraries. Additionally, it includes examples of Python code, variable rules, and input/output methods.

Uploaded by

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

Python Programming

Mr. K. Chandran
Assistant Professor & Technical Trainer
Madanapalle Institute of Technology & Science
Topics to be Covered

• Introduction to Python
• Python Installation
• First Program in Python
• Data Types
• Variables
• Numbers
Introduction to Python
• Python is a general-purpose interpreted,
interactive, object-oriented, and high-
level programming language.
• It was created by Guido van Rossum
during 1985- 1990.
• Python got its name from “Monty
Python’s flying circus”. Python was
released in the year 2000.
Introduction to Python

• Python is interpreted: Python is processed at


runtime by the interpreter. You do not need to
compile your program before executing it.
• Python is Interactive: You can actually sit at a Python
prompt and interact with the interpreter directly to
write your programs.
• Python is Object-Oriented: Python supports Object-
Oriented style or technique of programming that
encapsulates code within objects.
Introduction to Python

• Easy-to-maintain: Python's source code is fairly easy-


to-maintain.
• Portable: Python can run on a wide variety of
hardware platforms and has the same interface on
all platforms.
• Interpreted: Python is processed at runtime by the
interpreter. So, there is no need to compile a
program before executing it. You can simply run the
program.
Introduction to Python
• Extensible: Programmers can embed python
within their C,C++,Java script,ActiveX, etc.
• Free and Open Source: Anyone can freely
distribute it, read the source code, and edit
it.
• High Level Language: When writing
programs, programmers concentrate on
solutions of the current problem, no need to
worry about the low level details.
• Scalable: Python provides a better structure
and support for large programs than shell
scripting.
Introduction to Python

• Python Latest version is 3.10.7


• Python is Open Source Software
• Python has additional libraries also like matplotib for plotting
charts and graphs
• BeautifulSoup for HTML parsing and XML
• NumPy for scientific computing
• Pandas for performing data analysis
• SciPy for engineering applications, science, and mathematics
• Scikit for machine learning
• Django for server-side web development
• And many more..
Python Installation
For Windows & Mac:
• To install python in windows you need to download
installable file from https://www.python.org/downloads/
• After downloading the installable file you need to execute the
file.
For Linux :
• For ubuntu 16.10 or newer
• sudo apt-get update
• sudo apt-get install python3.8

• Alternatively we can use anaconda distribution for the python


installation
• http://anaconda.com/downloads
• Anaconda comes with many useful inbuilt libraries.
First Program in Python

• To write python programs, we can use any text


editors or IDE (Integrated Development
• Environment), Initially we are going to use IDLE
• Create new file in editor, save it as first.py
(Extensions for python programs will be .py)
First.py
print("Hello World from python")
Output :
Hello World from python
First Program in Python
This is an example of a print statement. It displays
a result on the screen. In this case, the result is
the words.
First Program in Python
Integrated Development Learning Environment (IDLE)
Is a graphical user interface which is completely written in
Python.
It is bundled with the default implementation of the python
language and also comes with optional part of the Python
packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation
Python shell to display with syntax highlighting
Datatypes in Python
Name Type Description
Integer Int Whole number
such as 0,1,5, -5
etc..
Float Float Numbers with
decimal points
such as 1.5, 7.9, -
8.2 etc..

String Str Sequence of


character
(Ordered) such as
“mits” , ‘college’ ,
“રાજકોટ” etc

Boolean Bool Logical values


indicating True or
False (T and F
here are capital
in python)
Datatypes in Python
Name Type Description
List List Ordered
Sequence of
objects, will be
represented
with square
brackets [ ]
Example : [ 18,
“mits”, True,
102.3 ]
Tuple tup Ordered
immutable
sequence of
objects, will be
represented
with round
brackets ( )
Example : ( 18,
“mits”, True,
102.3 )
Datatypes in Python
Name Type Description
Set set Unordered
collection of
unique objects,
will be
represented with
the curly brackets
{}
Example : { 18,
“mits”, True,
102.3 }
Dictionary dict Unordered key :
value pair of
objects , will be
represented with
curly brackets { }
Example :
{ “college”:
“mits”, “code”:
“054” }
Variables in Python

• A Python variable is a reserved memory location to


store values.
• Unlike other programming languages, Python has no
command for declaring a variable.
• A variable is created the moment you first assign a
value to it.
• Python uses Dynamic Typing so,
Variables in Python
• We need not to specify the data types to
the variable as it will internally assign the
data type to the variable according to
the value assigned.
• we can also reassign the different data
type to the same variable, variable data
type will change to new datatype
automatically.
• We can check the current data type of
the variable with type(variablename) in-
built function.
Rules for Variable Names

• Name cannot start with digit


• Space not allowed
• Cannot contain special character
• Python keywords not allowed
• Should be in lower case
Rules for Variable Names
Valid Identifiers Invalid Identifiers Reason for Invalid

totalSales ‘totalSales’ Quotes not allowed

totalsales total sales Spaces not allowed

salesFor2022 2022Sales Cannot begin with


digit
sales_for_2022 $2022Sales Shoud not begin
with a special
character other than
underscore.
Example of Python Variable

x = 10
print(x)
print(type(x)
Y = 123.456
print(y)
X = “MITS Institute of Engineering and Technology”
print(x)
print(type(x)
Example of Python Variable
Run in Terminal
Python.demo.py
Output
10
int
123.456
MITS Institute of Engineering and Technology
str
Python - Statements

Instructions that a Python interpreter can executes are


called statements.
A statement is a unit of code like creating a variable or
displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that
gives a value to n. The second line is a print
statement that displays the value of n.
Python - Expressions
-An expression is a combination of values, variables, and
operators.
A value all by itself is considered an expression, and also a
variable.
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2 7
>>> z=("hi"+"friend")
>>> print(z) hifriend
Python – Input/Output

INPUT: Input is data entered by user (end user) in the program.


In python, input () function is available for input.

Syntax for input() is:


variable = input (“data”)
Example:
>>> x=input("enter the name:") enter the name: george
>>>y=int(input("enter the number")) enter the number 3
#python accepts string as default data type. conversion is
required for type.
Python – Input/Output
OUTPUT: Output can be displayed to the
user using Print statement .
Syntax:
print (expression/constant/variable)
Example:
>>> print ("Hello") Hello
Python – COMMENTS

A hash sign (#) is the beginning of a comment.


Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating
percentage of an hour
Python does not have multiple-line commenting feature. You
have to comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too. # I said that already.
Python – DOCSTRING
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module,
function, class, or method definition. We must write
what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__ Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double. doc )
Function to double the value
Python – LINES AND INDENTATION
Most of the programming languages like C, C++, Java use braces
{ } to define a block of code. But, python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function
definitions or flow control.
Example :
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
Python – QUOTATION IN PYTHON
Python accepts single ('), double (") and triple (''' or """)
quotes to denote string literals. Anything that is
represented using quotations are considered as
string.

single quotes (' ') Eg, 'This a string in single quotes'

double quotes (" ") Eg, "'This a string in double quotes'"


triple quotes(""" """) Eg, This is a paragraph. It is
made up of multiple lines and sentences."""
Python – TUPLE ASSIGNMENT
An assignment to all of the elements in a tuple using a single
assignment statement.
Python has a very powerful tuple assignment feature that allows
a tuple of variables on the left of an assignment to be
assigned values from a tuple on the right of the assignment.
The left side is a tuple of variables; the right side is a tuple of
values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of
the assignments. This feature makes tuple assignment quite
versatile.
Naturally, the number of variables on the left and the number of
values on the right have to be the same.
Python – TUPLE ASSIGNMENT
Example
It is useful to swap the values of two variables. With
conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:
Swap two numbers

a=2, b=3
print (a,b)
temp = a
a=b
b = temp
print (a,b)
Python – TUPLE ASSIGNMENT
One way to think of tuple assignment is as tuple
packing/unpacking.
In tuple packing, the values on the left are ‘packed’ together in a
tuple:
>>> b = ("George", 25, "20000") # tuple packing
-In tuple unpacking, the values in a tuple on the right are
‘unpacked’ into the variables/names on the right:
>>> b = ("George", 25, "20000") # tuple packing >>>
(name, age, salary) = b # tuple unpacking
>>> name 'George'
>>> age 25
>>> salary
'20000'
Python – TUPLE ASSIGNMENT
-The right side can be any kind of sequence
(string,list,tuple)
Example:
-To split an email address in to user name and a domain
>>> mailid='[email protected]'
>>> name,domain=mailid.split('@')
>>> print name god
>>> print (domain) abc.org
Numbers of Python

The following are the supporting number formats:


• Integers
• Floating point
• Complex Numbers
• Decimal
• Rational
Numbers of Python
Keywords
False Class Finally Is Return

none Continue For Lambda try

True def From Nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


Print Method

• To print any data in output console, use print( ) method


Different formats

print("Sum of ",first_number,"and",second_number,"is",add)
Sum of 10 and 20 is 30
print("Sum of %d and %d is %d"%(first_number,second_number,add))
Sum of 10 and 20 is 30
print("Sum of {} and {} is {}".format(first_number,second_number,add))
Sum of 10 and 20 is 30
• Format specifiers are also supported
• {%d,%f,%s}

name = 'Peter'
age = 23
print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print('{name} is {age} years old')
Runtime Input

• To get any data in run-time, use input( ) method


• By default, all inputs will be in string format

a=input("Enter a number")
print(a) // string data
b=input()
print(b) // string data
Runtime Input
• To convert the string data into specific
format, use the conversion method

a=int(input("Enter a number"))
print(a) // int data
b=float(input())
print(b) // float data
Numbers in python : int

• Integers are zero, positive or negative whole numbers without a


fractional part and having unlimited precision
• 24 bytes of memory – default
>>> 0
0
>>> 100
100
>>> -10
-10
>>> 1234567890
1234567890
Numbers in python : int
• No spaces are allowed between any
digits Ex: a = 5 7 // Syntax Error
• No numbers should be started with
prefix of ‘0’ other than binary/octal/hexa
• Ex: a = 087 // Syntax Error
• Underscore are allowed between
numbers Ex: a = 5_7 // a=57
Numbers in python : int

• Integers can be represented in any of the three below


formats:
• binary (‘0b’)
• octal(‘0o’ or ‘0O’)
• hexadecimal (‘0x’ or ‘0X’)

a=0b111 print (a) // 7


b=0o12 print (b) // 10
b=0x12 print (b) // 18
Numbers in python : int
• To convert any string into ‘int’, use int ( )
function
• int(‘100’) // 100 Decimal
• int(‘100’,2) // 4 Binary
• int (‘74’,8) // 60 Octal
• int('123',16) // 291 Hexa
Numbers in Python : int

Decimal to Octal Conversion


Number Remainder
8 136 0
8 17 1
8 2 2
0
(136)10 = (210)8

Octal to Decimal Conversion

345

3*82
4*81
5*80
192+32+5 = 229
(345)8 = (229) 10
Numbers in Python : int
Example -1 Example -2
a = 10,20 a = 10_20_30
print(a) print(a)
Output Output
(10,20) #tuple 102030

Example -3 Example -4
a = 10_20_; a = 0o84;
print(a) print(a)
Output Output: Syntax Error
Syntax Error

Example -5
print(oct(74))
Output: 112
Numbers in Python : float

Float data type has fractional part


Positive and Negative real numbers with a fractional part denoted by
the decimal symbol (.) or scientific notation

Example :
123.56
3.142
-1.546
0.23
Numbers in Python : float
• The float beyond its max.size referred as
‘inf’,’Inf’,’INFINITY’ or infinity
Example
f=2e400
print(f)
inf
Numbers in Python : float

• Scientific Notation is used as a short representation to express floats having many digits

• Example

• a = 1e3
• print (a) # 1000.0
• a = 1e5
• print (a) # 100000.0
• a = 3.4556789e2
• print (a) # 345.56789

• To limit the fraction, use the following format.

• a=5.678848
• print('{:.2f}'.format(a))
• #5.68
Numbers in Python : float
• To convert any type into float, use float( )
function

• >>> float (‘5.5’) # 5.5


• >>> float (‘5’) # 5.0
• >>> float(‘1e3’) #1000.0
• >>> float('12e4') #120000.0
Formats
Number Format Output Description

3.1415926 (:.2f) 3.14 2 decimal places

3.1415926 (:+.2f) +3.14 2 decimal places with


sign
-1 (:+.2f) -1.00 2 decimal places with
sign
3.1415926 (:.0f) 3 No decimal
places(round)
5 (:0>2d) 05 Pad with 0’s on left

1000000 (:,) 1,000,000 Number format with


comma separator
0.25 (:.2%) 25.00% Format Percentage

100000000 (:.2e) 1.00e Exponent notation


+09
Numbers in Python : Complex Numbers
• It is a number with real and imaginary components
• 5 + 6j i.e 5 – real j – imaginary
• 16 bytes of memory – default
• Use only ‘j’ or ‘J’ as imaginary component
• Example :
• >>> a=5 + 2k
• >>> Syntax Error
• >>> a=5i + 2j
• >>> Syntax Error
• >>> a=5 + j
• >>> Syntax Error

• Arithmetic Operators can be applied for any complex numbers {+,-,


*,**,/}
• a = 6 + 4j
• a = a+2
• print(a) // 8 + 4j
Numbers in Python : Complex Numbers

Using ‘*’ operator


a=6 + 4j
a=a*2
print(a) // 12 + 8j i.e both real and imaginary will have updation
Using ‘**’ operator
a=6 + 4j
a=a**2
print(a) // 20+48j i.e both real and imaginary will have updation

Calculation:
= 36 + 24j + 24j + (16*-1)
= 36 + 48j – 16
= 20 + 48j
Numbers in python : Rational number

It is represented as a rational fraction m/n . i.e has integer value


Ex: 5/6

Fraction – automatically performs the simplification fraction .


9/18 -> 1/2

Always import the module before implementation

from fractions import Fraction


a=Fraction(5,6)
print(a) # 5/6

Example:
a=Fraction('1.33') # 133/100 a=Fraction(‘-1.5') # -3/2
Numbers in Python – Rational Number

Arithmetic operators of +, -, *, /, % and ** can be applied


from fractions import Fraction
a=Fraction(5,6) + Fraction(3,2) #a=7/3
b=a – Fraction(3,5) #b=26/15
c=b*Fraction(101,202) #c=13/15
d=c/b #d=1/2
e=d%a #e=1/2
f=Fraction(1,2)**Fraction(1,2) #f=0.70710
Python Operators
• Operators are the constructs which can
manipulate the value of operands.
• Consider the expression 4 + 5 = 9. Here,
4 and 5 are called operands and + is
called operator
Python Operators

• Python language supports the following types of


operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators
• ‘+ and –’ can be used in both unary and binary category

• Prototype '+'
• (int,int) -> int # 5 + 3 = 8
• (float,float)-> float # 5.6+2.3= 7.9
• +(int) -> int # +3 = 3
• +(float) -> float # +3.5=3.5
• +(complex) -> complex # +5j = 5j
• (complex+complex)->complex # 5j+3j = 8j

• Prototype '-'
• (int,int) -> int # 5 - 3 = 2
• (float,float)-> float # 5.6-2.3= 3.3
• -(int) -> -int # -3 = -3
• -(float) -> -float # -3.5= -3.5
• -(complex) -> -complex # -5j = -5j
• (complex-complex)->complex # 3j-5j = -2j
Arithmetic Operator {+,-}

Example -1 Example -2 Example -3


a = ++10 a = -10 a = 1020
print(a) -a print(‘Ans:’,a+10)
print(a) print(a)
Output Output
10 Output Output: 1030
Output: -10 1020

Example -4 Example -5
a = 10++10 a = 10
print(a) a+20 = 10
Output print(a)
Output: 20 Output
Output: Syntax
Error
Arithmetic Operator {*}
• Multiplication(*) operator can be used
only in the binary category.

Prototype

*(int,int) - > int


*(float,float) - > float
*(complex,complex) - > complex
Arithmetic Operator {*}

Example

a = 5*5 # prints a -> 25


a = 5--5 # prints a -> 10
a = 5.5*5.5 # prints a -> 30.25
a = 5 * 5.5 # prints a -> 27.5
a = 3j * 5j # prints a -> (-15+0j)
a = -5 * 5.5 # prints a -> -27.5

Uses
a =‘mits’
print(a*2) #mitsmits
Print(2*a) #mitsmit
Arithmetic Operators {‘/’}
Division(/) operator can be used only in the binary category.

Prototype
/(int,int) - > float
/(float,float) - > float
/(complex,complex) - > complex

Example

a = 13/5 # prints a -> 2.6


a = 3+10/5 # prints a -> 5.0
a = -10/4 # prints a -> -2.5
a = 10/-4 # prints a -> -2.5
a = -10/-4 # prints a -> 2.5
a = 123.5/-4 # a -> -30.875
a = 3/4 # prints a -> 0.75
Arithmetic Operators {‘//’}

Floor Division(//) operator can be used only in the


binary category. {Quotient}

Protype
//(int,int) - > int
//(float,float) - > float(Without values)
Arithmetic Operators {‘//’}
• Example
• >>> a = 10//5 # prints a -> 2
• >>> a = -10//4 # prints a -> -3
• >>> a = 10//-4 # prints a -> -3
• >>> a = -10//-4 # prints a -> 2
• >>> a = 123.5//4 #a -> 30.0
• >>> a = 123.5//-4 #a -> -31.0
• >>> a = 3//4 # prints a ->0

• Uses
• a =123
• b =a//10 #reduce unit digit
• print(b) # b -> 12
• a =123
• b =123//100 #gives MSB bit
Arithmetic Operators {‘%’}

Modulo(%) operator can be used only in the binary


category. {Remainder}
It takes the signature of denominator for answer.

Prototype
%(int,int) - > int
//(float,float) - > float

Formula
a%b = a – b * (a // b)
Arithmetic Operators {‘%’}

Example
>>> a = 10%3 # prints a -> 1
>>> a = 5%10 # prints a -> 5
>>> a = -10%3 # prints a -> 2
>>> a = 10%-3 # prints a -> -2
>>> a = -10%-3 # prints a -> -1
>>> a = -3%10 # prints a -> 7
>>> a = -3%-10 # prints a -> -3
>>> a = 3%-10 # prints a -> -7

Uses
a =123
b =a%10 # gives unit digit
print(b) # b -> 3
a =123
b =123%100 #Leaves MSB bit
Arithmetic Operators {‘**’}

Power(**) operator can be used only in the binary


category. {powered value}
Left operand is raised to the power of right

Prototype
**(int,int) - > int
**(float,float) - > float
**(complex,complex) - > complex
Arithmetic Operators {‘**’}
Example
>>> a = 10**2 # prints a ->100
>>> a = -2**2 # prints a -> -4
>>> a = -2**-2 #prints a -> -0.25
>>> a = 2**-2 # prints a -> 0.25
Operator Precedence

Priority Operator Associativity


1st Power ** Right to Left

2nd Multiplicative */% Left to Right

3rd Additive +- Left to Right


• Example k = 8//4+3-5*6+8
Solving, '*' and '//' first from left to right.
k = 2+3-30+8
Now solving, '+' and '-' from left to right
k = -17
Now solving '=' from right to left k is
made -17
Arithmetic Operators – Test Yourself

Example 1 Example 2 Example 3

a = 10*5-2+4//2 a= 10*5-2+4**2 a = -33%-148;


print(a) print(a) print(a)
Output 50 Output 64 Output -33

Example 4 Example 5
a = 113//-4; a = 5.6+3*4-2
print(a) print(a)
Output -29 Output: 15.600000.
Problems
1. Collect three run-time input from user.
Add together the first two numbers
and then multiply this total by the
third. Display the answer as “The
answer is :“ [answer]
2. Program to print only the added
fraction of any two number {Input:
2.356 3.5678 Output: 0.9238]
3. Program to print current hours, minutes and
seconds?.
4. Program to print the unit digit of a given number
{ Input: 1567 Output: 7}
5. Program to calculate the sum from ‘M’ number to
‘N’ number. {Input: M-5 N-10 Output: 45}
6. Ramesh’s basic salary is input through the
keyboard. His dearness allowance is 40% of basic
salary, and house rent allowance is 20% of basic
salary. Write a program to calculate his gross salary
Relational Operators
Relational Operators

• Relational operator will return answer as boolean


value{True or False}

Prototype Operators Supported


(int, int) -> boolean == != < > <= >=
(float,float) ->boolean == != < > <= >=
(complex, complex) ->boolean == !=
(bool, bool) -> boolean == != < > <= >
(str, str) -> boolean == != < > <= >=
Relational Operators
Example
>>> a = 10!=3 # prints a -> True
>>> a = 5.6<5.6 # prints a -> False
>>> a = -10>-3 # prints a -> False
>>> a = False<True # prints a -> True
Assignment Operators
Assignment Operators
Assignment operator is the one which helps to assign values
or expression to Lvalue of
variable

a = 1000

Lvalue[meaningful variable] = Rvalue[can be value or


variable]
Example:

a=5
b=a
#Both 'a' and 'b' will point the same object print(a,b)
Assignment Operator

Multiple Assignment:
a = b = c = 50 #a b and c has value of 50
a, b =100,50 # a=100 and b =50
Assignment Operators
Python supports the following shortcut
assignment operators: +=, -=, *=, /=,
%=, //=, **=

a=10
a+=10
# a= a+10
print(a) #a=20
Assignment Operators

a=10.5
a+=10 # a= a+10.5
print(a) #a=20.5

a=10
a-=10 # a= a-10
print(a) #a=0
Assignment Operators
x=‘wel’
y=‘come’
x+=y #x=x+y
print(x) #a=‘welcome’

a=10
a**=2 # a= a**2
print(a) #a=100
Logical Operators

Python supports three logical operators and, or, not


Output : Boolean Value {True or False)
Truth Table
A B A AND B A OR B NOT A

T T T T F

T F F T F

F T F T T

F F F F T
Logical Operators - Example
a=10 a=10 a=10
print(a<20 and a>5) print(a>20 and print(not a) #False
# True a<20) print(not -1) #False
#False

a=10 a=10
print(a<5 and print(a>5 or
((a:=15)>5)) ((a:=15)>5))
#False #True
print(a) #a=10 print(a) #a=10
Bitwise Operators
Bitwise Operators
• Bit–wise operations compute their
results on the individual bits – based on
integer operands
• Both Input and Output : Integers
• For Process: Binary format
Bitwise Operators

Truth Table

A B A|B A&B A^B ~A

0 0 0 0 0 1

0 1 1 0 1 1

1 0 1 0 1 0

1 1 1 1 0 0
Bitwise Operators
• A bitwise operation operates on one or more bit patterns at
the level of individual bits
• Let us assume x = 10 (0000 1010 in binary and
y = 4 0000 0100 in binary)
Bitwise Operators
Not (~) - If the ith bit is zero, it will change to 1 and
viceversa
AND (&) -> if both the bits in the compared position of
the bit patterns are 1 the bit in resulting patthern is 1,
otherwise 0 Ex:a=5=(101)2 b=3=(011)2 A&B=(001)2=1
OR -> Both bits are 0 the result will be 0therwise 1
XOR (^) -> If both bits are 0 or 1 the result bit pattern is 0
or otherwise 1
Left Shift (<<)-> shift some no of bits in the given pattern
to left and append 0 at end
Right Shift (>>)-> Shift some of the bits in the given
pattern to the right and append 1 at end
Bitwise Operators
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b # 12 = 0000 1100
print ("Line 1 - Value of c is ",c)
c = a | b # 61 = 0011 1101
print ("Line 2 - Value of c is ",c)
c = a ^ b # 49 = 0011 0001
print ("Line 3 - Value of c is ",c)
c = ~a # -61 = 1100 0011
Bitwise Operators
Output :

• Line 1 - Value of c is 12
• Line 2 - Value of c is 61
• Line 3 - Value of c is 49
Bitwise Operators

a=23
b = a>>1 #1011
print(b) #b=11
Bitwise Operators
a=23
b= a<<1 # 101110
Print(b) #b = 46
Membership Operators

The following are the membership operators


available in python:

in, not in
These operators are used to test whether a
value is found within a sequence or not

Example: Using String


Identity Operators
The following are the identity operators
available in python:
is , is not

These operators are used to check if a


particular value is of a certain class or
type
Identity Operators
Example:

a=101
b=101
print(a is b) #True
a=101
b=102
print(a is b) #False

a=101
b=101
print(a is not b) #False
Operators – Test Yourself
Example - 1 Example - 2 Example - 3

a = ‘mits’<‘Mits’ a= ‘5’ in ‘1115’ a = -2<<4;


print(a) print(a) print(a)
Output Output Output
False True -32

Example – 4 Example – 5
a = -5; a = 10
print(~a) b = a<<1 + 20//5
print(320)
Output
4 Output
Output: 320
Questions
1. Calculate CGST and SGST for a product and print the total
price to pay {CGST = SGST = 9%}

2. Write a program to read the marks of 5 subjects through


the keyboard. Find out the average and percentage of marks
obtained by the student. Assume maximum marks that can be
obtained by a student in each subject as 100.

3. Write a program to read a four-digit number through the


keyboard and calculate the sum of its digits
Questions - Contd

4. An ATM contains Indian currency notes


of 100, 500 and 1000. To withdraw cash
from this ATM, the user has to enter the
number of notes he/she wants of each
currency, i.e. of 100, 500 and 1000.
Write a program to calculate the total
amount withdrawn by the person from
the ATM in rupees.
5. Write a program to calculate age based
on input of date, month and year

You might also like