Python: Arithmetic and Logical Operators

How to perform arithmetic and logical operations on Python variables of different types

January 3, 2013 - 4 minute read -
python arithmetic-operators logical-operators

Table of Contents

Note: Python snippets were tested and run in Python 2.7. They may require some changes to be compatible with Python 3

Arithmetic Operators in Python

Addition, Subtraction, Division, Modulus, Power (number raised to some power)

Addition

>>> 6 + 3
9
>>> 6.4 + 5
11.4

Python knows that if you ask to add an int to float, it makes sense to answer in float

Subtraction

>>> 5 - 4
1

Multiplication

>>> 6 * 4
24

Division

>>> 18/2
9
>>> 19/2
9

What? That’s wrong! Nope. Python will always return int if both numerator and denominator are of type int If one of them is in float then it will return answer in float

>>> 19.0/2
9.5

Modulus

>>> 7 % 5
2
>>> 10 % 5
0

Finding integer raised to the power

>>> 6**2
36
>>> 3.14*20
62.800000000000004

Complex expression, a mixture of multiple operators

>>> 2 + 3 * 4
14

Hey! I meant, add 3 to 2 and then multiply it with 4. How do I assign preference of operations? Answer is to surround them by ().

>>> (2 + 3) * 4
20

Order of precedence

  • ** has highest, then * and / (whichever comes first in your expression), then + and -. Key to not get confused by operator precedence is to use (). This also helps in future when you come back to your code after months and have no clue what you did.

We can also perform operations on str types. + will join two strings.

>>> "su" + "san"
'susan'

Logical Operators in Python

Let’s consider two variables i and j to understand the meaning of various comparison operators.

  • i > j
    • returns True if i is strictly greater than j, else returns False
  • i >= j
    • returns True if i is greater than or equal to j, else returns False
  • i < j
    • returns True if i is strictly less than j, else returns False
  • i <= j
    • returns True if i is less than or equal to j, else returns False
  • i == j
    • returns True if i is equal to j, else returns False
  • i != j
    • returns True if i is not equal to j, else returns False

More logical operators in Python

Assume i and j are bool variables

  • i and j
    • returns True if both i and j are True, else returns False
  • i or j
    • returns True if either of i or j is True, else returns False
  • not i
    • returns True if i is False, returns False if i is True

Next post will discuss yet another widely used data-type in Python: Strings


Note: This is a part of what I learned in an online Open Course Ware offered by MIT on edX. Its for my personal reference & also for those who would like to revisit the course.