Python

Python Operators

Operators are used to perform operations on data

Arithmetic Operators:

OperatorExampleAnswer
Addition(+)a=1, b=2 print(a+b)3
Subtraction(-)a=1, b=2 print(b-a)1
Multiplication(*)a=2, b=3 print(a*b)6
Division(/)a=6, b=3 print(a/b)2
Floor division(//)a=17, b=2 print(a//b)8
Modulus(%)a=17, b=2 print(a%b) 1
Exponentiationa=2, b=3 print(a**b) 8

Assignment Operators: Assigns values to variables. Operators can also be combined such as += when assigning values

OperatorExampleAnswer
=a=2 print(a)2
+=a=2, a+=2 print(a)4

Comparison Operators: Compares two values

OperatorExampleAnswer
equal(==)print(1==2)false
not equal(!=)print(1!=2)true
greater than(>)print(1>2)false
less than(<)print(1<2)true
greater than or equal to(>=)print(1>=1)true
less than or equal to(<=)print(2<=2)true

Logical Operators: Compares statements

OperatorExampleAnswerDescription
andprint((1==2) and (2==2))falseBoth conditions true
orprint((1==2) or (2==2))trueOne condition is true
notprint(not((1==1) and (2==2)))falseNegation

Membership Operators: checks for a sequence in object

OperatorExampleAnswerDescription
inprint(1 in (1,2,3))trueChecks for membership in a sequence
inprint(4 in (1,2,3))falseChecks for membership in a sequence
not inprint(4 not in (1,2,3))trueChecks for membership in a sequence

Identity Operators: Compare the objects

OperatorExampleAnswerDescription
isa=[‘p’,’q’]
b=[‘p’,’q’]
c=a

print(a is b)

false
Compares the objects not the values

print(a is c)trueCompares the objects not the values
is notprint(a is not b)trueCompares the objects not the values

Bitwise Operators: Compare binaries

Bitwise operators are and (&)  , or (|) ,  xor (^)  ,  not (~) , Shift left (<<) , Shift right (>>)