官术网_书友最值得收藏!

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
主站蜘蛛池模板: 交口县| 长海县| 余干县| 万全县| 凌海市| 洱源县| 军事| 陇川县| 高安市| 五莲县| 郴州市| 蓬安县| 湘乡市| 五指山市| 徐汇区| 贵州省| 胶南市| 永福县| 河北区| 衡水市| 芦溪县| 内黄县| 吐鲁番市| 德惠市| 江川县| 柏乡县| 芜湖县| 吴堡县| 蒙阴县| 诏安县| 麦盖提县| 淮北市| 海淀区| 海晏县| 德清县| 大田县| 凤台县| 彭阳县| 忻城县| 平武县| 唐山市|