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
Python knows that if you ask to add an int
to float
, it makes sense to answer in float
Subtraction
Multiplication
Division
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
Modulus
Finding integer raised to the power
Complex expression, a mixture of multiple operators
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 ()
.
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.
Logical Operators in Python
Let’s consider two variables i
and j
to understand the meaning of various comparison operators.
i > j
- returns
True
ifi
is strictly greater thanj
, else returnsFalse
- returns
i >= j
- returns
True
ifi
is greater than or equal toj
, else returnsFalse
- returns
i < j
- returns
True
ifi
is strictly less thanj
, else returnsFalse
- returns
i <= j
- returns
True
ifi
is less than or equal toj
, else returnsFalse
- returns
i == j
- returns
True
ifi
is equal toj
, else returnsFalse
- returns
i != j
- returns
True
ifi
is not equal toj
, else returnsFalse
- returns
More logical operators in Python
Assume i
and j
are bool
variables
i and j
- returns
True
if bothi
andj
areTrue
, else returnsFalse
- returns
i or j
- returns
True
if either ofi
orj
isTrue
, else returnsFalse
- returns
not i
- returns
True
ifi
isFalse
, returnsFalse
ifi
isTrue
- returns
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.