August 23, 2021, Learn eTutorial

1079

The main objective of this python number tutorial is to educate the concept of number datatype and its conversion in the python programming language. Also will learn about some arithmetic operations used to manipulate this number datatype.

In python, when a variable is assigned with a number then it comes under the Python Number Datatype. A number data type comprises of an integer value, float value, and a complex type value which are precisely stated as

- int
- float
- complex

- Int data type holds integer values (zero, positive, and negative whole numbers) only
- No fractional part is included
- Length is boundless

```
#i is a variable of type int
i1 = 10
i2 = 525
print("integer 1 = ",i1)
print("integer 2 = ",i2)
```

**Output**

integer 1 = 10 integer 2 = 525

- Contains floating-point numbers
- Includes fractional parts
- Decimal points bounds precisely to 15 decimals

```
#i is a variable of type int
f1 = 10.01
f2 = 525.25
print("floating point number 1 = ",f1)
print("floating point number 2 = ",f2)
```

**Output**

floating point number 1 = 10.01 floating point number 2 = 525.25

Complex numbers are numbers comprises of a real part and an imaginary part to take the form a+ib where a and b are real numbers and b is associated with an imaginary unit, i. Example and output.

- Comprises of real part(a) and imaginary part(b)
- The form is a +ib
- The Imaginary unit is ‘i’

```
C1 =-5-6i
C2 = 4+3i
print("Complex number 1 = ",C1)
print("Complex number 2 = ",C2)
```

**Output**

Complex number 1 = -5-6i Complex number 2 = 4+3i

One of the unique features in most programming languages is type conversion. **Type conversion** simply can be defined as changing the data type of one object to another datatype, subjected to various operations or evaluations. Conversion can be done either implicitly or explicitly based on the requirements for hassle-free operations.

**Implicit conversion**, otherwise known as *coercion*, is generally defined as the conversion of one python datatype to another based on expression or evaluation as required by a compiler or interpreter. Python programming language supports the type conversion though it has some pitfalls which we will discuss further.

Let us consider the below example in detail to understand more about python coercion. Suppose we need to find the average of two numbers n1 and n2 which are integer datatype. The result could be a fractional number, which stored as a float value. Python automatically declares the resulted value into float making the programmer hassle-free from error. This type of implicit conversion is usually termed as coercion.

```
#Type coercion example
n1 = 2
n2 = 3
print(“Average of” n1 “and” n2 “ = ”,(n1+n2)/2)
```

**Output**

Average of 2 and 3 = 2.5

In some cases, python needs to explicitly convert one python datatype to another based on the requirement. Such type of conversion is generally termed **explicit conversion** or *typecasting*. Python has some built-in function which helps to convert data types explicitly. They are listed below

**int( arg )**- converts the data type of arg to integer**float(arg)**- converts the data type of arg to floating-point**complex(arg1, arg2)**- converts the datatype of arg1 and arg2 to complex type where arg1 holds the real part, and arg2 holds the imaginary part.

```
#Type casting example
a = 10
b = 5.3
c = 4+5i
#Conversion
x= float (a)
y=int(b)
z=complex of (a)
#Printing output with corresponding data type
print( x "belongs to",type(x))
print( y "belongs to",type(y))
print( z "belongs to",type(z))
```

**Output**

10.0 belongs to <class 'float'> 5 belongs to <class 'int'> 10+0i belongs to <class 'complex'>

We have studied in mathematics about decimals and their operations like addition, subtraction, multiplication ….. But when learning a programming language we have given a new name to decimal numbers called **floating-point numbers**. We typically consider floating-point numbers as decimals themselves. But in reality there exist some differences, while learning machine languages

We know that machines can only understand the binary representation ie, 0 and 1. Floating-point numbers are treated in binary form as well. Hence the binary floating-point calculation is quite different from the typical decimal calculation.

```
A = 1.10
B = 2.20
C = A+B
print("C =",C)
```

**Output**

C = 3.3000000000000003

From the above example on adding 1.10 and 2.20, we are expecting 3.30 as its sum. But the output we got is 3.3000000000000003. This is how fractional numbers are represented in binary forms. And so we have to roughly round the value to 3.30. So we can say that the decimal values stored in the computer are not accurate.

we can sort this inaccuracy of floating-point numbers by simply importing a decimal module. Unlike binary floating-point, the decimal module has programmer altered precision which maintains significance that helps to perform the calculation as we studied in schools. Hence the decimal module is very useful for accounting purposes, financial applications, and so on.

```
import decimal
A = decimal.Decimal('1.1')
B = decimal.Decimal('2.2')
C = 3
D = 3.14
print("A =",A)
print("B =",B)
print("A+B = ",A+B)
print("A+C = ",A+C)
print("A+D = ",A+D)
```

**Output**

A = 1.1 B = 2.2 A+B = 3.3 A+C = 4.1 print("A+D = ",A+D) TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

**Note**: Decimal operators work with integers but floating-point numbers have to be converted to decimal instances.

Given below table summarizes the difference between decimal and floating-point numbers.

Decimal | Float |
---|---|

Have exact representation | Does not have an exact representation |

Precision length varies on user need | Precision length is fixed |

Includes idea of significant places | Does not support significant places |

Partial cover on published standards | Full cover on published standards |

Decimal operations are slower | Floating-point operations are faster |

Eg: 1.10 + 2.20 = 3.30 | Eg: 1.1 + 2.2 = 3.3000000000000003 |

Like the decimal module, another important module associated with number datatype is the fraction module.

A numerator and a denominator constitute a fraction that we have studied in our earlier classes. Python also supports fractional calculations by importing a module called fractions.

Different ways of creating fraction instances are listed below.

```
import fractions
A = fractions.Fraction(1,2)
B = fractions.Fraction (3,4)
print("A =",A)
print("B =",B)
print("A+B =",A+B)
```

**Output**

A = 1/2 B = 3/4 A+B = 5/4

```
import fractions
A = fractions.Fraction('5/7')
B = fractions.Fraction('3/8')
print("A =",A)
print("B =",B)
print("A+B =",A+B)
```

**Output**

A = 5/7 B = 3/8 A+B = 61/56

```
import fractions
A = fractions.Fraction(2.5)
B = fractions.Fraction(1.5)
print("A =",A)
print("B =",B)
print("A+B =",A+B)
```

**Output**

A = 5/2 B = 3/2 A+B = 4

```
import fractions
A = fractions.Fraction('.5')
B = fractions.Fraction('1.5')
print("A =",A)
print("B =",B)
print("A+B =",A+B)
```

**Output**

A = 1/2 B = 3/2 A+B = 2

Python also presents two other important modules that are in fact the back born of mathematical activities. These modules are **math** and **random** which are used to perform trigonometric functions, logarithms, probabilities, etc. Functions associated with math modules are tabulated here for easy reference.

Sl No | Functions | Description | Example |
---|---|---|---|

1 | abs(x) / fabs(x) | returns the absolute value of x | abs(5.6) => 5 |

2 | ceil(x) | returns the ceiling value of x | ceil(5.6)=>6 |

3 | floor(x) | returns the floor value of x | floor(5.6)=>5 |

4 | exp(x) | returns the exponential value x ;e^{x} |
exp(x)=e^{x} ; e^{0} = 1 |

5 | log(x) | returns the logarithmic value of x, for x>0 | log2(8) =3 |

6 | log10(x) | returns the logarithmic value of x with base 10,for x>0 | log10(100)=2 |

7 | sqrt(x) | returns square root of x, x>0 | sqrt(16)=4 |

8 | Pow(x,y) | returns power of x to y | pow(2,3)=8 |

9 | round(x,[n]) | returns the round value of X irrespective of sign | ound(5.6) =6 round(-5.4) =-5 |

10 | max(n1,n2,n3…) | returns the largest value | max(1,5,9) =9 |

11 | min(n1,n2,n3…) | returns the smallest value | min(1,5,9)=1 |

12 | modf(x) | returns the fractional part of a floating number | modf(5.6)=0.6000000 |

13 | sin() | returns sine of argument in radians | sin 0 |

14 | cos() | returns cosine of argument in radians | cos 0 |

15 | tan() | returns tangent of argument in radians | tan 0 |

16 | hypot(a,b) | returns the hypotenuse value of arguments .Type equation here. | hypot(3,4) =5 |

17 | degrees() | converts radian value to degree and returns degree value | |

18 | radians() | convert degree to radian and returns radian value |

Python contains a collection of functions that are used to generate or operate random numbers which are widely used in gaming applications, testing applications, security and privacy applications, etc. Functions to manipulate random numbers are given in the below table.

Sl No | Function | Description |
---|---|---|

1 | choice(sequences) | returns a random number from a string, list, tuple. |

2 | randrange(start,stop,step) | |

3 | random() | returns a random float number,0<=X<1 |

4 | seed([x]) | generates the same random number by saving the state of random function |

5 | shuffle(list) | used to rearrange the list |

6 | uniform(x,y) | generates a random floating-point number between x and y |