regularpython@gmail.com
Numbers
Number data types are used to store integer, float and complex values. In python, we don’t need to mention the type of data. Numbers are immutable we can’t modify the data once we declare it.
Number data types are,
Ø int
Ø long
Ø float
Ø complex
int:
This type is used to store positive or negative numbers with no decimal points.
Example:
a = 10
b = 20
Long:
This type is used to store unlimited integer data and followed by uppercase or lowercase L.
In python3 the long() function is not available. So in python3 long and int, both are the same. So you just need to use the int() function in python3.
In python3 you just need to declare an integer value and you don’t worry about the memory allocation whether it would be int or long
Example:
Python 2.x
a = 10L
b = 20L
python 3.x
a = 10
b = 20
Float:
If we want to take decimal points also than we go with the float data type.
Example:
Ø a = 10.5
Ø b = 5.3
Complex:
Complex data types are used to store real and imaginary values.
Example:
a = x+yj
Where x is called the real part and y is called the imaginary part.
a = 5+10j
Number Type Conversion
Converts one data type into another data type is called data type conversion.
X = ‘10’ (String data type)
int(x) : convert x to integer number
Output = 10
float(x): Convert x to float number
Output = 10.0
complex(x): Convert x to complex number
Type of Errors in Numbers
ZeroDivisionError:
This error is raised when a value is a division with zero then we get this type of error.
How to handle ZeroDivisioError?
1. Mostly avoid a value to division with zero.
2. Use the try-except block to control the exception.
Example:
a = 5/0
output:
Traceback (most recent call last):
File "E:\Repository\test\test\test.py", line 2, in <module>
a = 10/0
ZeroDivisionError: division by zero
ValueError (float type conversion):
This error is raised when we convert string to float. This is the most important error in type conversion.
Example:
float(‘5a’)
output:
Traceback (most recent call last):
File "E:\Repository\test\test\test.py", line 2, in <module>
a = float('5a')
ValueError: could not convert string to float: '5a'
ValueError (int type conversion):
This is the most important error raised in number type conversion.
Output:
Int(‘5a’)
Traceback (most recent call last):
File "E:\Repository\test\test\test.py", line 2, in <module>
a = int('5a')
ValueError: invalid literal for int() with base 10: '5a'