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

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
主站蜘蛛池模板: 高雄县| 安义县| 洪洞县| 涞水县| 汉沽区| 蛟河市| 密山市| 偃师市| 东兴市| 长寿区| 商水县| 周宁县| 华安县| 塔城市| 砚山县| 和林格尔县| 峡江县| 玉林市| 观塘区| 德保县| 含山县| 军事| 来宾市| 岳普湖县| 广德县| 牟定县| 乌恰县| 石台县| 炎陵县| 长阳| 安溪县| 昌邑市| 通道| 奇台县| 麟游县| 马公市| 临泽县| 巍山| 绥江县| 太白县| 岗巴县|