0% found this document useful (0 votes)
11 views

Basic & Operator in Python

Uploaded by

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

Basic & Operator in Python

Uploaded by

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

What is python?

==> Python is a programming language like c,c++,java.


==> Python is a general purpose programming language.
==> it is programming language used for developing any type of
software.
1. Windows based standalone applications
2. Console based applications
3. Web applications
4. Games
5. IOT (Internet of Things)
6. AI (Artifical Int)
7. DataScience
8. Mobile Apps

==> Python is high level programming langauge.


==>all high level languages are in english.
==>high level langages are portable
==> portablility allows you to develop and
run python applications on different hardware.

==> Python is a multiparadigm programming language.


==> programming paradigm define set
of rules and for writing programs.

==> python is a general purpose,multiparadigm and


high level programming language.

Python Featues
=============
1. Easy
a. Easy to Learn
b. Easy to Code
a. Easy to Learn
==> Simple English
==> No Complex syntax
a. The statements not end with ;
b. no explict datatypes for creating variables
c. there is no { } for defining blocks

b. Easy to code
==> less coding
C python
= ======
//Swaping logic x=10
void main() y=20
{ x,y=y,x
int x=10,y=20;
int z;
z=x;
x=y;
y=z;
}

C Java Python
#include<stdio.h> class Test
void main() {
{ public static void main(String args[]) print("Hello World")
printf("Hello World"); {
} System.out.println("Hello World");
}}

2. Free and Open Source

Free ==> Python software Free to download, you can download this software from
www.python.org

Q: What is Open Source?

Source Code or Source Program

Q: What Source Code or Source Program?

==> Any program written in high level langauge is source program.


==> after translating this source program we get executable program.
==> Python software source code is open to public.
==> This allows to develop new technologies using python.
==> Python is an object oriented programming language.
==> Every datatype in python is class and data is represented as objects.
Q: What is object?
Q: What is class?
Q: What is object oriented programming?
==> classes and objects are building blocks of an object oriented programming
languages.
==> an object is a real world entity.
==> in object oriented application development data is represented as objects.
==> every object is having two characterstrics.
1. properties
2. behaviour
==> properties define the state/data of object.
==> behaviour define the functionality/operations of object.
==> class is model of the object.
==> class is encapsulated with properties and behaviour of object.
==> class define the structure of object object.
==> class is blueprint of object.
==> class is a datatype. using class we can create any number of objects.
==> class is container which define the properties and behaviour of objects.

What is variable?

=> variable is an identifier.


=> variable is a named memory location.
=> variable is an identifier, which is used to identify object.

How to create variables in python?

=> variable in python is created by assigning value/object.

variable-name=<value>

==> every variable in python is reference variable.


==> these variables does not hold values, it hold address of object.
int datatype

 int is a predefined class in python.


 This class is available in built-ins module(lib).
 The default module imported by any python program is built-ins
module.

Note: in python we can variables by assigning value.

 int is an immutable datatype


 after creating integer object the value cannot be modified. It
represent a constant.
 Because of immutability, these objects can be shared.
 Because of constants/immutability, these objects can be
shared between multiple variables.
id()  id() is predefined function in python. This function
return object identity which is called address. Every object is
having unique address.

>>> n1=100
>>> n2=200
>>> n1
100
>>> n2
200
>>> id(n1)
1614851552
>>> id(n2)
1614853152
>>> n3=100
>>> id(n3)
1614851552
>>> n1=300
>>> id(n1)
59547536
type() : type() is predefined function in python. This function
return type of object hold by variable.
>>> type(n1)
<class 'int'>
>>> type(n2)
<class 'int'>
>>> type(n3)
<class 'int'>
>>> type(n4)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
type(n4)
NameError: name 'n4' is not defined

Q: How to create variable in python?

Ans: In python variables are created by assigning value.


Q: What is immutability?

Ans: Which cannot modified is called immutability.

Q: int datatype is mutable or immutable?

immutable

Q: is integers are shared or not?

shared or constant pooling or object pooling.

 The size of int datatype is unlimited length. Objects are dynamic.

>>> n1=999999999999999999999
>>> n1
999999999999999999999

>>> n1=256
>>> id(n1)
1614854048
>>> n2=256
>>> id(n2)
1614854048
>>> x=257
>>> y=257
>>> id(x)
59546480
>>> id(y)
59547616
>>>

float
===

 float is a standard data type. This datatype is used to reserve


memory for real numbers or floating point value.
 This datatype exists in built-ins module.
 float is a name of the class, which is used for creating float objects.
 This datatype represents constant or immutable.
 Because of immutable these values/objects can be shared.
 This object is created by assigning float value.
 This float value is represented in two formats.
 Fixed
 Expo
 This datatype reserve memory of unlimited length.
float
===

 float is a standard data type. This datatype is used to reserve


memory for real numbers or floating point value.
 This datatype exists in built-ins module.
 float is a name of the class, which is used for creating float objects.
 This datatype represents constant or immutable.
 Because of immutable these values/objects can be shared.
 This object is created by assigning float value.
 This float value is represented in two formats.
 Fixed
 Expo
 This datatype reserve memory of unlimited length.

>>> x=1.5
>>> type(x)
<class 'float'>
>>> y=15e-1
>>> y
1.5
>>> type(y)
<class 'float'>
>>>
 The value of e is 10
 N=15e-10  15x10 pow -1  1.5

>>> z=1.234567895678956789

>>> z
1.2345678956789568

 the number decimal places are 16 (double precision)

Float is immutable because of that it is sharable.

complex
=======

 this datatype is used for representing complex number.

complex number is having two values/properties/attributes.

1. real
2. imag

complex number is created with the following syntax

real+imagj

real and imag values are float type.


>>> c1=1+2j

>>> type(c1)

<class 'complex'>

>>> comp1=1+2j

>>> comp1

(1+2j)

>>> type(comp1)

<class 'complex'>

>>> comp1.real

1.0

>>> comp1.imag

2.0

>>> comp1.real=1.5

Traceback (most recent call last):

File "<pyshell#21>", line 1, in <module>

comp1.real=1.5

AttributeError: readonly attribute

>>> comp1.imag=2.5

Traceback (most recent call last):

File "<pyshell#22>", line 1, in <module>

comp1.imag=2.5

AttributeError: readonly attribute

>>> comp3=3j
>>> type(comp3)

<class 'complex'>

>>> comp3

3j

>>> comp3.real

0.0

>>> comp3.imag

3.0

>>>

 it is constant or immutable whose values are never


changed.

Boolean
======

 this datatype is used to represent Boolean values.


 Boolean variables are created by assigning Boolean values.
 Boolean values are represented in python with 2 keywords.
 True
 False

Rollno  int RID  int


Name  str Pname  string
Course  str Address  string
Feefloat isReserved  True/False
FeePaid  bool (True/False)

>>> a=True
>>> b=False

>>> type(a)

<class 'bool'>

>>> type(b)

<class 'bool'>

String
=====

 A string collection of characters.


 These characters can be alphabets, digits or special
characters.
Eg: name,hno,username,password,address,…
 Python allows to represent string in three ways.
o Within single quotes
o Within double quotes
o Within 3 single quotes or 3 double quotes
 Within single quotes
o ‘string’
o Within single quotes double quotes can be embedded

>>> str1='naresh'
>>> str2='python 3.8'
>>> type(str1)
<class 'str'>
>>> type(str2)
<class 'str'>
>>> str3='123'
>>> type(str3)
<class 'str'>
>>> str4='python is a programming language'
>>> str5='python is high level programming language
SyntaxError: EOL while scanning string literal

>>> str6='python is a "scripting" language'


>>> str6

 within double quotes

 Within double quotes we can embedded single quotes.

Python is a ‘scripting’ language

>>> str1="python is 'scripting' language"

>>> str2='python is "scripting" langauge'

>>> str1

"python is 'scripting' language"

>>> str2

'python is "scripting" langauge'

 Within double or single quotes we can represent a string


with one line

triple single quotes or double quotes

 It is also represented as doc string

>>> str1='''python

is

programming

language'''

>>> print(str1)
python

is

programming

language

>>> str2="""python

is

high level

programming

langauge"""

>>> print(str2)

python

is

high level

programming

langauge

>>>

 Within three single quotes we can insert double quotes


 Within three double quotes we can insert single quotes
I/O Operations in python

input ==> the information given to the


program(keyboard,file,database,web,..sources)

process ==> performing operations

output ==> the information given by the program/result

 In input data is flow inside the program


 In output data is flow outside the program

print()
=====

 print() is a predefined function in python.


 this function is used to display or print information/data within file.
 The default file used for printing is console/monitor.
 It can also be used to print in different files.
 This function is available in built-ins module/lib.

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

 Print function required the following inputs.


o Values
o Sep
o End
o File
o Flush
 Values: print function receive zero or more values
 Sep: print function use sep, when it print more than one
value. The default sep is space
 End : string appended after the last value, default is newline
\n
 File : sys.stdout  console (sys is module, stdout=con)
 Flush : output operation is done using buffer, inorder to
auto flush the content of buffer the value of flush is True,
default it is false.

>>> print()

>>> print(100)

100

>>> print(100,200)

Changing sep:
===========

>>> print(100)

100

>>> print(100,200)

100 200

>>> print(100,200,300,400,500,600,700)

100 200 300 400 500 600 700

>>> print(100,200,300,400,500,600,700,sep=':')

100:200:300:400:500:600:700

>>> print(100,200,300,400,500,600,700,sep='\n')

100

200
300

400

500

600

700

>>> print(100,200,300,400,sep='\t')

100 200 300 400

>>> print(100,200,300,400,500,sep=',')

100,200,300,400,500

>>> print(100,sep=',')

100

Chaning end
==========

print(100)

print("Python")

print(200,end=':')

print("Python")

print()

print(100,200,"Python",sep=',',end=':')

print(300,400,"Django")
Output:

100

Python

200:Python

100,200,Python:300 400 Django

Changing file
==========
 the default file is console.
we can use any other file in order write or print data.

Flush : Send output from buffer to file

print("Hello Python")

f=open("d:\\file1.txt","w")

print("Hello Python",file=f,flush=True)
Working in scripting mode or programming mode in IDLE (IDE)

 IDLE stands for Integrated Development Learning


Environment. This is default IDE which comes with Python
software. IDE is a editor.
 How to write script/program in idle.
o In Menu bar  select File  New File
o It open scripting windows/program
window
o Write a script and save program with
ext .py(source program)
o Every python file is saved with ext .py (source
program)
 In order to execute program
o In Menu bar  select Run  Run Module(F5)
o This compile and Interpret and execute python
program.
 Every python program is called one module.

Q: What is indentation?

 Indentation is a space.
 Every statement in python starts at 1st column
 The statement should not start with space.
 Space define a block, only blocked statements are given
space.

How to define comments in python?

 Python allows to define comments using #


 Comments are ignored by python translator.
 It is single line comment
# print("Hello")

def myFun():

''' This is my function in python'''

print("Hello")

print(myFun.__doc__)

print(print.__doc__)

print(input.__doc__)

print(int.__doc__)

 Three single quotes or double quotes are using to define doc


string. For every function,class or module we provide
documentation, which is defined using doc string. This doc
string get stored in one variable/attribute called __doc__
# program to add two numbers

n1=100

n2=200

n3=n1+n2

print(n1,n2,n3)
input()
======

 this function is used to read data from keyboard.


 Read string from standard input(keyboard)

Syntax:

input(prompt=None)

 Prompt is a string which is displayed on console.


 Using input, we can read only one value from keyboard.
 It will return this value as a string

Ex1:

a=input()

b=input()

print(a)

print(b)

print(type(a))

print(type(b))

output:

100

200

100

200

<class 'str'>

<class 'str'>
Eg2:

a=input()

b=input("Enter b value")

print(a)

print(b)

print(type(a))

print(type(b))

Ex3:

# write a program/script for adding two numbers

n1=input("Enter first number")

n2=input("Enter second number")

n3=n1+n2

print(n1,n2,n3)

output:

Enter first number100

Enter second number200

100 200 100200


Conversion Functions:
=================

1. int() : this function is used to convert integer represented as string to


integer and float to integer.
a. String to integer
b. Float to integer

Syntax1: int(str,base=10)
Syntax2: int(num)

Syntax1 convert string to integer. That string should contain the integer
with base 10(decimal number)

Syntax2 convert integer to integer or float to integer

Ex1:

>>> n1=int(100)

>>> n2=int(1.5)

>>> print(n1,n2)

100 1

>>> n2=int(1.987)

>>> n2

Ex2:

>>> s1="65"

>>> n1=int(s1)

>>> print(type(s1),type(n1))

<class 'str'> <class 'int'>


>>> print(s1,n1)

65 65

Ex3:

# write a program or script to add two numbers

a=input("Enter first number")

b=input("Enter second number")

n1=int(a)

n2=int(b)

n3=n1+n2

print(n1,n2,n3)

c=a+b

print(a,b,c)

>>> n1=87

>>> n2="87"

>>> a=int(n2)

>>> print(n1,n2,a)

87 87 87

>>> n1=65

>>> n2=0o101

>>> print(n1,n2)

65 65

>>> print(n1,oct(n2))

65 0o101
>>> x="65"

>>> n3=int(x)

>>> y="0o101"

>>> n4=int(y)

Traceback (most recent call last):

File "<pyshell#23>", line 1, in <module>

n4=int(y)

ValueError: invalid literal for int() with base 10: '0o101'

>>> n4=int(y,base=8)

>>> n4

65

>>> print(n4,oct(n4))

65 0o101

>>> n5=26

>>> n6=0x1a

>>> print(n5,n6)

26 26

>>> n7="0x1a"

>>> n8="26"

>>> x=int(n8)

>>> y=int(n7)

Traceback (most recent call last):


File "<pyshell#33>", line 1, in <module>

y=int(n7)

ValueError: invalid literal for int() with base 10: '0x1a'

>>> y=int(n7,base=16)

>>> print(x,y)

26 26

>>> print(x,hex(y))

26 0x1a

>>> b1=9

>>> b2=0b1001

>>> print(b1,b2)

99

>>> print(b1,bin(b2))

9 0b1001

>>> b3="0b1001"

>>> b4=int(b3)

Traceback (most recent call last):

File "<pyshell#43>", line 1, in <module>

b4=int(b3)

ValueError: invalid literal for int() with base 10: '0b1001'

>>> b4=int(b3,base=2)

>>> print(b1,hex(b4))

9 0x9
>>> print(b1,bin(b4))

9 0b1001

>>>
# write a program or script to add two binary numbers

b1=input("Enter first binary number")

b2=input("Enter second binary number")

n1=int(b1,base=2)

n2=int(b2,base=2)

n3=n1+n2

print(bin(n1),bin(n2),bin(n3))

Ouput:

Enter first binary number0b100

Enter second binary number0b101

0b100 0b101 0b1001


float()

 This function is used to convert float representation of


string to float and integer to float.

# write a program to find area of circle

r=float(input("Enter R"))
area=3.147*r*r
print("area of circle is ",area)

s1="1.5"
f1=float(s1)
s2="12"
f2=float(s2)
s3="15e-1"
f3=float(s3)
s4="1.5e0"
f4=float(s4)
print(f1,f2,f3,f4)
i1=12
f5=float(i1)
print(f5)
# write a program to find area of triangle

base=float(input("Enter base of triangle"))


height=float(input("Enter height of the triangle"))
area=0.5*base*height
print(area)
s1="123"
i1=int(s1)
s2="1.5"
f1=float(s2)
print(type(s1),type(s2))
print(type(i1),type(f1))
print(i1,f1)

complex()
========

 This function is used to convert string to complex.


 This function is used to construct complex number using
real and img values.

s1="1+2j"

c1=complex(s1)

print(type(s1),type(c1))

print(s1,c1)

# adding two complex numbers

comp1=complex(input("Enter first complex number"))

comp2=complex(input("Enter second complex number"))

comp3=comp1+comp2

print(comp1,comp2,comp3)

real1=1.5

img1=2.5

c1=complex(real1,img1)

real2=1.5

img2=1.2

c2=complex(real2,img2)

print(c1,c2)
bool()

 This function is used to convert int to boolean and boolean


to boolean

>>> x="True"

>>> b=bool(x)

>>> type(x)

<class 'str'>

>>> type(b)

<class 'bool'>

Expl: bool function cannot convert string to Boolean. It will do


conversion using ascii value of alphabet.

>>> n1=1

>>> b=bool(n1)

>>> type(n1)

<class 'int'>

>>> type(b)

<class 'bool'>

>>> n1

>>> b

True
>>> bool(True)

True

>>> bool(1)

True

>>> bool(0)

False

>>> bool(100)

True

>>> bool(200)

True

>>> bool(0)

False

>>> bool("False")

True

str()

 This function is used to convert int,float,complex boolean to


string.

s1=str(100)

s2=str(1.5)

s3=str(1+2j)

s4=str(True)

print(s1,s2,s3,s4)

# find total and avg of student


rno=int(input("Enter rollno"))

name=input("Enter name")

sub1=int(input("Enter sub1"))

sub2=int(input("Enter sub2"))

sub3=int(input("Enter sub3"))

total=sub1+sub2+sub3

avg=total/3

print(rno,name,sub1,sub2,sub3,total,avg)

PYTHON OPERATOR

Operators in python are classified into different categories.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
8. Conditional Operators

Q: What is operator in Python?

 Python is an object oriented programming language.


 In object oriented programming language data is represented as
objects. An object is an instance of class. Every data type in python is
a class and data is objects.
 These objects are operated using special functions defined inside
class, these special functions are called operator functions.
 Every operator is bind with a function available inside class/data
type.
>>> 100+200
300
>>> a=100
>>> b=200
>>> a.__add__(b)
300
>>> a.__sub__(b)
-100
>>> a-b
-100
>>>

>>> a=1.5

>>> b=1.2

>>> a+b

2.7

>>> a.__add__(b)

2.7

>>>

1. Arithmetic Operators
 These operators are used to perform arithmetic operations.
 These are binary operators, which operate on two operands.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Float division
// Floor division
% Modular
** Power of Operator or expo operator
 Always operators are eval based on the precedence of operators.
+ operator is used to perform two operations.

1. Adding numbers
2. Concat sequence
+ operator is used to perform two operations.

1. Adding numbers
2. Concatenating sequences (String, List, Tuple,..)

# adding numbers

res1=100+200

res2=1.5+2.2

res3=(1+2j)+(1+3j)

print(res1)

print(res2)

print(res3)

# concatenation of strings

# it two operands are string it perform concatenation

str1="python"

str2="java"

str3=str1+str2

print(str1,str2,str3)

str3=str1+str(3.9)

print(str3)

# when ever arithmetic operation is done on numbers

# the result is return as broader type


# int,float,complex ==> complex => float => int

res1=10+20 # int+int=int

res2=10+1.5 # int+float=float

res3=10+(1+2j) # int+complex=complex

print(res1,res2,res3)

res4=1+2.4+(1+2j)

print(res4)

res1=10+2.5

print(res1)

res2=int(10+2.5)

print(res2)

print(type(res1),type(res2))

- Operator : it is used for subtracting numbers

res1=100-200

res2=1.5-1.2

res3=(2+1j)-(1+0j)

print(res1,res2,res3)

*operator is used to perform two operation


1. multiplying numbers
2. repeating sequences( String, List, tuple,…)
n1=5*2 # int*int=int

n2=1.2*1.3 # float*float=float

n3=(1+2j)*(1+1j) # complex*complex=complex

print(n1,n2,n3)

str1="python"

str2=str1*5 # string*int = string

print(str1)

print(str2)

print("*"*40)

print("-"*40)

/ division operator, this operator is used to divide two numbers,


it divide two numbers and get the result in float. It is called float
division operator.

res1=4/2 # int/int=> float

res2=4.0/2.0 # float/float ==> float

res3=4.0/2 # float/int ==> float

res4=4/2.0 # int/float ==> float

print(res1,res2,res3,res4)
print(type(res1),type(res2),type(res3),type(res4))

res5=7/2 # int/float ==> float

print(res5)

The following script generate zerodivisionerror because we


cannot divide number with zero

res1=5/0

print(res1)

res1=0/2

print(res1)

res2=0.0/0.0

print(res2)

// This is also division operator. This is called floor division


operator. It perform division operation and return result int
type.

res1=5/2 # ==> int/int ==> float

res2=5//2 # int//int ==> int

print(res1)

print(res2)

res3=5.0//2 # float//int ==> int ==> float

print(res3)

res4=5//2.0 # int//float ==> 2 ==> 2.0


print(res4)

print(type(res1),type(res2),type(res3),type(res4))

% modulus operator  this operator is used to find rem

res1=5%2

res2=5%3

print(res1)

print(res2)

res3=4%2

print(res3)

res1=2.5%2

print(res1)

** power of operator (OR) expo operator

a=3**2

print(a)

b=3**-2

print(b)
Relational Operators

 Relational operators used to compare the state/value of one object


with another objects (OR) comparing values.
 Relational operators return Boolean value(True/False)
 Using relational operator we can Boolean expression
 An expression which return boolean value is called Boolean
expression.

Operator Meaning
> Greater than
< Less than
>= Greater than equal
<= Less than or equal
!= Not Equal
== Equal

 These operators are used to compare numbers and sequences (string,


list,..)

b1=100>200

b2=200>100

b3=100<200

b4=200<100

b5=100>=100

b6=200<=200

b7=100>=101

b8=200<=198

print(b1,b2,b3,b4,b5,b6,b7,b8)

b9='A'=='A' # 65==65

b10='A'<'B' # 65<66
print(b9,b10)

b11="abc"=="abc"

b12="abc"=="ABC"

print(b11,b12)

Logical Operators

 Logical operators are used to combine two or more conditions or


boolean expressions.

Operators Meaning
and Logical and operator
or Logical or operator
not Logical not operator

Truth table of logical operators

Opr1 Opr2 Opr1 and opr2 Opr1 or opr2


True True True True
True False False True
False True False True
False False False False

sub1=70

sub2=80

sub3=90

b1=sub1<40 or sub2<40 or sub3<40

b2=sub1>40 and sub2>40 and sub3>40

print(b1,b2)

b3=True or False
b4=True and True

b5=True or False or True

b6=True and False

print(b3,b4,b5,b6)

b7=1 and 0

print(b7)

b8=100 and 200 and 300 and 400

print(b8)

b9=True and True

b10=True and False

print(b9,b10)

b11=100 or 200

b12=0 or 200

print(b11,b12)

opr1 not opr1


True False
False True

b1=True

b2=not b1

b3=not b2

print(b1,b2,b3)
Bitwise Operators

 These operators are used to perform bitwise operations.


 It eval expression by converting into bits.

Operator Meaning
>> Bitwise Right shift operator
<< Bitwise Left shift operator
& Bitwise and operator
| Bitwise or operator
~ Bitwise not operator
^ Bitwise XOR operator

>> Right shift operator

 This operator is used to shift number of bits towards right side.


 This operator is used to decrement the value by removing bits.

Syntax:

Opr>>n
n1=12

n2=n1>>1

print(n1)

print(n2)

print(bin(n1))

print(bin(n2))

n3=n1>>2

print(n3)

print(bin(n3))

Formula : num/2 pow n

Ex: 12>>1  12/2  6


Ex: 24>>4  24/16  1

<< Left shift operator

 This operator is used to shift number of bits towards left side.


 By shifting number of bits left side, the value is incremented.

Syntax:

Opr<<n
Formula : num*2 pow n  15*2 pow 2  15*4 60

n1=15

n2=n1<<2

print(n1)

print(n2)

print(bin(n1))

print(bin(n2))
Bitwise &(and) ,| (or) ,^ (XOR)

 These operators are used to perform operations converting into


bits.
Truth table of &,|,^

Opr1 Opr2 Opr1&opr2 Opr1|opr2 Opr1^opr2


1 1 1 1 0
0 0 0 0 0
1 0 0 1 1
0 1 0 1 1

a=5
b=4
c=a&b
print(a,b,c)
print(bin(a),bin(b),bin(c))

x=10
y=5
z=x|y
print(x,y,z)
print(bin(x),bin(y),bin(z))

p=10
q=4
r=p^q
print(p,q,r)
print(bin(p),bin(q),bin(r))

Assignment Operators (OR) Augmented assignment


statements

Augmented assignment is the combination, in a single statement, of a


binary operation and an assignment statement.
+=,-=,*=,/=,//=,%=,>>=,<<=,&=,|=,^=,**=,=
a=15
a+=1 # a=a+1
b=20
b-=5 # b=b-5
c=30
c/=3 # c=c/3
d=40
d//=3 # d=d//3
e=7
e%=2 # e=e%2
f=5
f**=2
print(a,b,c,d,e,f)

Identity Operators

 Identity operators are used to compare identity or address of two


variables.
 is
 is not
a=10
b=20
c=a==b
print(c)
d=10
e=a==d
print(e)
x=a is b
y=a is d
print(x)
print(y)
a=10
b=10
print(id(a))
print(id(b))
print(a is b)
print(a==b)

list1=[10,20,30]
list2=[10,20,30]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(list1==list2)
list3=list1
print(id(list1))
print(id(list3))
print(list1 is list3)

Membership Operators

 Membership operators are used to find given element/value exists


in a given sequence or collection.
 in
 not in
 These members operators return Boolean values(True/False)
str1="python" # sequence datatype
b1="o" in str1
b2='e' in str1
print(b1)
print(b2)
b3="e" not in str1
print(b3)

Assignment expressions or walrus operator( :=)

 This operator is introduced in python 3.8 version


 There is new syntax := that assigns values to variables as part of a
larger expression. It is affectionately known as “the walrus
operator” due to its resemblance to the eyes and tusks of a walrus.

a=10
b=5
e=(c:=a+b)*(d:=a-b)
print(a,b,c,d,e)
Conditional Operator Or Conditional Expression

Conditional expressions (sometimes called a “ternary operator”) have the


lowest priority of all Python operations.
Syntax:
Expression1 if Test else Expression2
if test is True, it eval expression1 otherwise eval expression2

#finding max of two numbers


n1=int(input("Enter first number"))
n2=int(input("Enter second number"))
n3=n1 if n1>n2 else n2
print(n1,n2,n3)
# write a program to find input number is even or odd
num=int(input("Enter any number")) # 4
print(num,"is even") if num%2==0 else print(num,"is odd")

# write a program to find input character is vowel or not


ch=input("Enter any character")
print("vowel") if ch in "aeiouAEIOU" else print("not vowel")
# Multiple statements are defined by separating with ;
print("Hello");print("Bye") if True else print("Python")
# Multiple if operators
print("A") if False else print("B") if False else print("C")

# write a program to find max of three numbers


n1=int(input("Enter first number"))
n2=int(input('Enter second number'))
n3=int(input("Enter third numbre"))
print(n1,"is max") if n1>n2 and n1>n3 else print(n2,"is max") if n2>n3
else print(n3,"is max")
# write a program to find input character is alphabet, digit or
special character

ch=input("Enter any character") # 7


print("Alphabet") if ch>='A' and ch<='Z' or ch>='a' and ch<='z' else
print("Digits") if ch>='0' and ch<='9' else print("Special Character")

# write a program to find input year is leap or not


a=int(input("Enter the year"))print("Leap") if(a%4==0 and a%100!=0)
or (a%400==0) else print("not a leap")
Operator precedence

The following table summarizes the operator precedence in Python, from


lowest precedence (least binding) to highest precedence (most binding).

Operators in the same box have the same precedence.

Operator Description
:= Assignment expression
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, >=, Comparisons, including membership tests and
!=, == identity tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
Multiplication, matrix multiplication, division,
*, @, /, //, %
floor division, remainder
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index:index],
Subscription, slicing, call, attribute reference
x(arguments...), x.attribute
(expressions...),
Binding or parenthesized expression, list
[expressions...], {key: value...}, display, dictionary display, set display
{expressions...}
5 4 ^

12O - O =12.O
X= 4 2 << 1

b 2

4) ° (s

9 3

>7

You might also like