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
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.