Saturday, May 29, 2021

Numbers in Python

Python as a calculator 
---------------------- 

 

Interpreter can act as a calculator. Numbers 

such as 2, 4, and 30 have type `int` while 

5.0 and 1.6 are of type `float` 

>>> 2 + 2 

4 

>>> 50 - 5*6 

20 

>>> (50 - 5*6) / 4 

5.0 

>>> 8 / 5  # division always returns a floating point number 

1.6 

Division using `/` always returns a float. 

To discard fractional part, use `//` (floor 

division). Calculating the remainder is done 

via `%` (modulus operator). 

>>> 17 / 3  # classic division returns a float 

5.666666666666667 

>>> 

>>> 17 // 3  # floor division discards the fractional part 

5 

>>> 17%3  # the % operator returns the remainder of the division 

2 

>>> 5*3 + 2  # result * divisor + remainder 

17 

Calculating powers is also possible. 

 

>>> 5 ** 2  # 5 squared 

25 

>>> 2 ** 7  # 2 to the power of 7 

128 

`=` sign is used to assign value to a 

variable 

>>> width = 20 

>>> height = 5 * 9 

>>> width * height 

900 

If a variable is not "defined" (assigned a 

value), trying to use it will give you an 

error 

>>> n  # try to access an undefined variable 

Traceback (most recent call last): 

  File "<stdin>", line 1, in <module> 

NameError: name 'n' is not defined 

Python always tries to display result as a 

floating number 

>>> 3 * 3.75 / 1.5  # int * float / float 

7.5                 # results to a float 

>>> 7.0 / 2  # float / int 

3.5          # results to a float 

You may do a continuous calculation because the 
last printed expression is assigned to `_` 
 
NOTE: don't assign a value to `_` 

>>> tax = 12.5 / 100 

>>> price = 100.50 

>>> price * tax 

12.5625             # this is assigned to `_` 

>>> price + _       # you can access the last value by calling `_` 

113.0625 

>>> round(_, 2) 

113.06 

Other number types supported 

1. decimal 
2. fraction 
3. complex numbers 
 
e.g: 

 

>>> 3 + 5j - 5 - 5j 

(-2+0j) 

>>> 

 

Operations on numbers 

--------------------- 

 

Ways of limiting 

decimal places 

>>> import math 

>>> pi = math.pi 

>>> pi 

3.141592653589793 

>>> 

>>> print('{0:.2f}'.format(pi)) 

3.14 

>>> print('%.2f' % pi) 

3.14 

>>> print(round(pi,2)) 

3.14 

>>>  

Rounding numbers 

>>> round(123.454665575777) 

123 

>>> round(123.454665575777, 5) 

123.45467 

>>>  

Extracts decimal part 

>>> x 

2.34 

>>> int(str(x).partition('.')[2]) 

34 

>>>  

Converts int to binary 

and vice versa 

>>> bin(23) 

'0b10111' 

>>> int('10111', 2) 

23 

>>> 

No comments:

Post a Comment