Numbers

The Python interpreter can also act as a calculator. You just have to type an expression and it will return the value. Parentheses ( ) are used to do the grouping, as shown in the following example:

>>> 5 + 5
10
>>> 100 - 5*5
75
>>> (100 - 5*5) / 15
5.0
>>> 8 / 5
1.6

The integer numbers are of the int type and a fractional part is of the float type.

In Python, the division (/) operation always returns a float value. The floor division (//) gets an integer result. The % operator is used to calculate the remainder.

Consider the following example:

>>> 14/3
4.666666666666667
>>>
>>> 14//3
4
>>>
>>> 14%3
2
>>> 4*3+2
14
>>>

To calculate powers, Python has the ** operator, as shown in the following example:

>>> 8**3
512
>>> 5**7
78125
>>>

The equal sign (=) is used for assigning a value to a variable:

>>> m = 50
>>> n = 8 * 8
>>> m * n
3200

If a variable does not have any value and we still try to use it, then the interpreter will show an error:

>>> k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
>>>

If the operators have mixed types of operands, then the value we get will be of a floating point:

>>> 5 * 4.75 - 1
22.75

In the Python interactive console, _ contains the last printed expression value, as shown in the following example:

>>> a = 18.5/100
>>> b = 150.50
>>> a * b
27.8425
>>> b + _
178.3425
>>> round(_, 2)
178.34
>>>

Number data types store numeric values, which are immutable data types. If we do this, Python will allocate a new object for the changed data type.

We can create number objects just by assigning a value to them, as shown in the following example:

num1 = 50
num2 = 25

The del statement is used to delete single or multiple variables. Refer to the following example:

del num
del num_a, num_b
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset