Everybody should be familiar with numbers. Numbers are simple mathematical values which are used to represent a quantity or amount of something. If you have experience of programing with any other programing language, then probably you would know about them. Python’s numbers are quite similar with them. The numbers are used to count some objects, keep track you bank balance, the distance to Moon and any other numeric quantity.
In Python, numbers are a category of similar type, not a single object type. Python provides supports for literals as well as regular numeric types such as integer and float.
Variables and Basic Expression
A variable is a named location to store some values. In Python, a variable is created when a value is assigned to them. As name suggests, the value stored in variables is changeable in nature. Variables are objects in Python and must be assigned before their use in expression. For example:
>>> a = 3 # variables are created >>> b = 4
In Python, if anything is written after a # sign, it is considered as comments and ignored. Comments are an important part of programing because they improve the readability of the code.
Now we’ll use our previously declared variables, a and b in an expression. The values of the variables have been changed when they are used in an expression:
>>> a + 1, a − 1 # Addition (3 + 1), subtraction (3 − 1) (4, 2) >>> b * 3, b / 2 # Multiplication (4 * 3), division (4 / 2) (12, 2.0) >>> a % 2, b ** 2 # Modulus (remainder), power (4 ** 2) (1, 16) >>> 2 + 4.0, 2.0 ** b # Mixed-type conversions (6.0, 16.0)
This whole operation could be performed only because the variables, a and b, had been previously initialized. If we use an undeclared variable, then Python reports an error:
>>> a * 2 Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> a*2 NameError: name 'a' is not defined
It is must to assign a value to a variable before using it. Here, we are using another example to illustrate operator grouping and conversions:
>>> b / 2 + a # Same as ((4 / 2) + 3) 5.0 >>> b / (2.0 + a) # Same as (4 / (2.0 + 3)) 0.8
In the first example, Python automatically decides the grouping according to default operator precedence rules. In this case “/” is processed first and then the “+” will be processed. Python 3.X always perform a true division so the answers are in rational format.
In second expression, we are using parentheses around the + operator to perform addition operator first. Because one of the value is 2.0 or floating point number, Python converts all other values to float and return an answer.
Chained and Normal Comparison
In addition to the mathematical operation, comparison operations on numbers play very important role in Python. In comparison operation, the magnitude of the numbers is compared and then a Boolean result is returned: true or false, which is used in further execution of the program:
>>> 1 < 2 # Less than operation True >>> 2.0 >= 1 # Greater than or equal operation True >>> 2.0 == 2.0 # Equality comparison True >>> 2.0 != 2.0 # Not equal False
Except these normal operations, Python allows chain multiple comparison operations to perform range tests. Python allows us to combine together multiple operands to compare with each other as a range test. For example:
Listing 1: Representing the chained comparison
>>> X = 2 >>> Y = 4 >>> Z = 6 >>> X < Y < Z # Chained comparisons: range tests True >>> X < Y > Z False >>> 1 < 2 < 3.0 < 4 True >>> X < Y > Z False >>> X < Y and Y > Z False >>> 1 < 2 < 3.0 < 4 True
If you are using floating point numbers then these operations may work only after some type conversions or other messages to compare meaningfully:
>>> 1.1 + 2.2 == 3.3 # Shouldn't this be working?... False >>> 1.1 + 2.2 # Close to 3.3, but not exactly 3.3000000000000003 >>> int(1.1 + 2.2) == int(3.3) # this will work True
In Python division is done by using two operators:
True Division (X/Y):This division operator always keeps remainders in floating point numbers regardless of types. This type of division is called true division.
Floor Division( X//Y):When this operator is used, it truncates fractional remainders down to their floor, regardless of types. The result of this operation depends on the type of its operands.
Examples of division operation are given below:
Listing 2: Representing the examples of division operations
>>> 10 / 4 # keeps remainder 2.5 >>> 10 / 4.0 # keeps remainder 2.5 >>> 10 // 4 # truncates remainder 2 >>> 10 // 4.0 # truncates to floor 2.0
Generally // operator is referred as floor operator because it truncates the result to its floor. A floor value is the closest whole number below the true result. This operation mostly round down the value, not strictly truncate and this matters for negatives:
>>> 5 / 2, 5 / −2 (2.5, −2.5) >>> 5 // 2, 5 // −2 # rounds to first lower integer (2, −3) # 2.5 becomes 2, −2.5 becomes −3 >>> 5 / 2.0, 5 / −2.0 (2.5, −2.5) >>> 5 // 2.0, 5 // −2.0 # result is float (2.0, −3.0)
Python gives its integer types a very exotic facility: python integers support unlimited size. Unlike other languages, Python will convert any integer which is too large to store to a built in long integer type. This facility of unlimited size gives Python immense power to work with very large calculations in integer numbers. For example, you can raise a number to such a large power as given below:
>>> 8**200 4149515568880992958512407863691161151012446232242436899995657329690652811412908146399707048947103794288197886611300789182395151075411775307886874834113963687061181803401509523685376
You cannot even imagine about these type of calculations in other languages. Because of this extra calculation, usually integer math for large number is substantially slower than normal.
Complex numbers are mostly used in scientific and engineering applications and are distinct core type in Python. These numbers consists two floating point numbers: real and imaginary part. To represent them a j suffix is added to the imaginary part. For example, a complex number with a real part of 3 and -3 as imaginary part is written as 2+ -3j. Some examples of complex maths is given below:
>>> 1j * 1J (-1+0j) >>> 2 + 1j * 3 (2+3j) >>> (2 + 1j) * 3 (6+3j)
Complex numbers are complex in nature as their name suggests so their operations. We should use the tools provided by Python in cmath module. This module is a complex version of normal math module. In most of the programming domains, the use of these numbers is rare unless they are needed in some sort of scientific calculations.
Some Other Built-in Tools
Python has some standard library modules and built-in functions for numeric processing. For example, pow and abs function are used to compute power and absolute values respectively. Some of these functions are given below from built-n math library:
Listing 3: Representing the built-in functions of math and other modules
>>> import math >>> math.pi, math.e (3.141592653589793, 2.718281828459045) >>> math.sin(2 * math.pi / 180) 0.03489949670250097 >>> math.sqrt(144), math.sqrt(2) (12.0, 1.4142135623730951) >>> pow(2, 4), 2 ** 4, 2.0 ** 4.0 (16, 16, 16.0) >>> abs(-42.0), sum((1, 2, 3, 4)) (42.0, 10) >>> min(3, 1, 2, 4), max(3, 1, 2, 4) (1, 4)
To use some functions, user will have to import the required module as we imported math in Listing 3 example. But a user can access built-in functions such as pow and abs are always available without imports.
Numeric types are very important part of Python language. Number operations should be called the backbone of the modern computer science. In this discussion, we learned about various operations and their effect on numbers. We also discussed about some built-in functions and some functions of math module. This is a very diverse topic, so you should go or some reference manuals of Python to deeply understand this topic.