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.4Python knows that if you ask to add an int to float, it makes sense to answer in float
Subtraction
>>> 5 - 4
1Multiplication
>>> 6 * 4
24Division
>>> 18/2
9
>>> 19/2
9What? 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.5Modulus
>>> 7 % 5
2
>>> 10 % 5
0Finding integer raised to the power
>>> 6**2
36
>>> 3.14*20
62.800000000000004Complex expression, a mixture of multiple operators
>>> 2 + 3 * 4
14Hey! 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
20Order 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
Trueifiis strictly greater thanj, else returnsFalse
- returns
i >= j- returns
Trueifiis greater than or equal toj, else returnsFalse
- returns
i < j- returns
Trueifiis strictly less thanj, else returnsFalse
- returns
i <= j- returns
Trueifiis less than or equal toj, else returnsFalse
- returns
i == j- returns
Trueifiis equal toj, else returnsFalse
- returns
i != j- returns
Trueifiis not equal toj, else returnsFalse
- returns
More logical operators in Python
Assume i and j are bool variables
i and j- returns
Trueif bothiandjareTrue, else returnsFalse
- returns
i or j- returns
Trueif either ofiorjisTrue, else returnsFalse
- returns
not i- returns
TrueifiisFalse, returnsFalseifiisTrue
- 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.