Working with Python Operators

Srikanth Thyagarajan
3 min readFeb 15, 2021

Arithmetic operators

As the name implies, arithmetic operators are for doing arithmetic; addition, subtraction, multiplication, division, and others.

  • The modulus is the remainder after division. So, for example, 11 % 5 is 1 because if you divide 11 by 2 you get 5 remainder 1. That 1 is the modulus(sometimes called the modulo).
  • The exponent is ** because you can’t type a small raised number in code. But it just means “raised to the power of” in the sense that 3**2 is 32 or 3 squared, which is 3*3 or 9. And of course 3**4 would be 3*3*3*3 or 81.
  • Floor division, indicated by //, is integer division in that anything after the decimal point is truncated (ignored). The term truncated in this sense means “cut off,” without any rounding. For example, in regular division 9/5 is 1.8. But 9//5 is just 1 because the .8 is just chopped off, it doesn’t even round up the 1 to a 2.

Example

a = 21
b = 10
print(a + b) // 21
print(a - b) // 11
print(a * b) // 231
print(a / b) // 1.909
print(a % b) // 10
print(a ** b)// 350277500542221
print(a // b)// 1

Comparison operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators They are decisions based on absolute facts based on comparisons. The operators Python offers to help you write code that makes decisions

Example

a = 21
b = 10
c = 0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"

if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"

if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"

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

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

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

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

Boolean operators

The Boolean operators work with Boolean values (True or False) and are used to determine if one or more things is True or False.

if a > b:
print("a is greater than b")
else:
print("a is less than b")

--

--