2. Basic Types: Numbers
Integers
Now that we have shown that and are equal to and in Python, it might come as no surprise that the type is actually a subtype of the type that includes all the integers; . Similar to being a shorthand for boolean, is a shorthand for integer.
Integer defintionAn integer is defined as a number that can be written without a fractional component. In computer science, integer refers to a data type that describes some range of mathematical integers.
Like in mathematics, integers in Python support a variety of mathematical operations. Their use is very similar to how you would use them on a calculator, barring some exceptions.
The most common mathematical operators supported by :
Operator | Name | Usage | Returns |
Addition | The sum of and . | ||
Subtraction | subtracted by . | ||
Multiplication | multiplied by . | ||
Division | divided by . | ||
Exponentiation | to the power of |
Less common, but still useful operators supported by :
Operator | Name | Usage | Returns |
Modulo or Modulus | The remainder of divided by . | ||
Floor Division or Integer Division | The result of divided by rounded down (floored) to . |
Let's take a look at the operators in action, most of them should be familiar.
Operator examplesSimple integer addition:
>>> 10 + 10
|
20
|
>>> 10 + 10 + 10
|
30
|
Just like we used parentheses in boolean expressions we can use them here to modify the order of evaluation.
Parentheses examplesWe can use parentheses to subvert operator precedence:
>>> 4 + 4 * 4
|
20
|
>>> (4 + 4) * 4
|
32
|
Even when parentheses are not necessary it might be useful to add them anyway to make your code more explicit.
>>> 36 - (-12)
|
32
|
Booleans in Python inherit all functionality from integers, so it's possible to perform calculations with and . They will simply evaluate to and within mathematical expressions.
Boolean examplesAs a subtype of , inherits the same functionality:
>>> True + False
|
1
|
>>> True * 3 / True
|
3.0
|
Or visit omptest.org if jou are taking an OMPT exam.