How Can We Help?
Number data types store numeric values only in number objects. Number objects are created when we assign a value to them.
Number Object Syntax:
<variable_name> = <numerical type value>
For example, a=6 and b=9, where “a” and “b” are the number objects.
Note: If we change the value of a number data type, the result of it is a newly allocated object. So, we can say the number data type is immutable.
Numerical Types in Python:
Python version 3 supports three different numerical types.
Types | Description | Example |
---|---|---|
int (signed integers) | It is positive or negative whole numbers (integers) with no decimal point. | 10, -2, -0x270, 0x20 |
float (floating point actual values) | The float value is written with a decimal point dividing the integer and fractional parts. | 2.5, 3.0, -2.5, 32.3+e18, 70.2-E12, 32.54e100 |
complex (complex numbers) | It is a complex number (x+yj) format where x is a real and y is an imaginary part. | 2.2j, 2+5j, 9.322e-36j, 3e+26J, 4.53e-7j, -.6545+0J |
Note: In the above examples, “E or e” denote the power of 10 like 2.5e2 = 2.5 x 102 = 250.
A type as long (long integers ) is an integer of unlimited size, written like integers and followed by an uppercase (L) or lowercase (l). To avoid confusion with the number 1, python mainly displays long integers with an uppercase L. This type is used in Python version 2 only.
Example, 51924361L, -0x19323L, 0xDEFABCECBDAECBFBAEL
Number Type Conversion in Python:
Sometimes we need to convert a number from one type to another to satisfy our calculation or function requirement. Python supports the following number type conversions. To convert any number in one type to another, we must pass the number inside the parentheses.
Type Conversion Function | Description |
---|---|
int(number) | It converts a number into a plain integer. |
float(number) | It converts a number into a floating-point number. |
complex(number) | It converts a number into a complex number with the actual part as a number and the imaginary part as a zero. We can take real and imaginary parts by “complex(number1, number2)” and number1=real part and number2=imaginary part. |
Int(number) Function Example:
x=2.5
print( int(x))
Output
2
In the above example, variable x is a float number; after converting it into an integer, the result is 2.
float(number) Function Example:
x=2
print(float(x))
Output
2.0
In the above example, variable x is an integer number; after converting it into a float, the result is 2.0.
complex(number) Function Example:
x=2
print(complex(x))
print(complex(x,6))
Output
(2+0j)
(2+6j)
In the above example, the variable x is an integer number. After converting it into a complex number, the result is 2+0j, where 2 is the actual number, and 0j is the imaginary part not mentioned in conversion syntax. When we use the syntax as a print(complex(x,6)), the natural part is x, and the imaginary part is 6, so the output shows 2+6j.
We can pass the expression in type conversion also.
int(expression) Function Example:
x=1
print(int(1/5))
Output
0
In the above example, x/5 is an expression that passes in the int() function to convert the result into an integer.
We can’t directly use string object value in the calculation; we need to first convert a string value into a number by using type conversion and then use it in the calculation.
Example
percentage="5"
x=10
print("5% of x is ", x*int(percentage)*0.01)
Output
5% of x is 0.5
In the above example, variable x is a number object, and a percentage is a string object, which is converted into an integer by “int(percentage)” to use in the calculation.
Note: Python version 2 uses a long function as long(number), which converts a number into a long integer. This function is not supported in python version 3.
long(float('1.1'))
Output
1L
Delete function of Number Data Type:
We can delete the reference to a number object using the del function. This function can delete a single object or multiple objects.
Syntax:
del <variable_name>
del <variable_name1>, <variable_name2>
Example
x=12
del x
print(x)
Output
Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
print(x)
NameError: name ‘x’ is not defined
In the above example, the output shows an error because after deleting variable x, it is not present in memory.
Example
x=10
y=20
del x,y
print(x)
print(y)
Output
Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
print(x)
NameError: name ‘x’ is not defined
Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
print(y)
NameError: name ‘y’ is not defined
The above example shows an error because they are not present in memory after deleting variables x and y.
Functions in Number Data Types
Python supports the following function for number data types.
- Mathematical Functions
- Random Number Functions
- Trigonometric Functions
- Mathematical Constants
1) Mathematical Functions
Python supports the following mathematical functions, which perform mathematical calculations. These functions are primarily used to make games and inventory calculation-related applications. Most of the functions are mathematical, so we need to import the math module to use them.
- abs(x) : It returns an absolute value of x, the (positive) distance between x and zero.
- ceil(x) : It returns the ceiling of x as the smallest integer, not less than x.
- exp(x) : It returns the exponential of x like ex.
- fabs(x) : It returns an absolute value of x. It works like abs(x); the only difference is that it works with the math module.
- floor(x) : The floor of x: the largest integer not greater than x.
- log(x) : It returns the natural logarithm of x, for x> 0.
- log10(x) : It returns the base-10 logarithm of x for x> 0.
- max(x1, x2,…) : It returns the largest value from a given argument (the value closest to positive infinity).
- min(x1, x2,…) : It returns the smallest value from a given argument (the value closest to negative infinity).
- modf(x) : It returns the fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.
- pow(x, y) : It returns the value of x**y.
- round(x [,n]) : It returns the x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
- sqrt(x) : It returns the square root of x for x > 0.
Now let’s take a quick examples on each mathematical function in the list above.
abs() Function Example:
print(abs(-45.3))
Output
45.3
ceil() Function Example:
import math
print(math.ceil(-46.5))
Output
-46
exp() Function Example:
import math
print(math.exp(-5))
Output
0.006737946999085467
fabs() Function Example:
import math
print(math.fabs(math.pi))
Output
3.141592653589793
floor() Function Example:
import math
print(math.floor(-48.36))
Output
-49
log() Function Example:
import math
print(math.log(102.3))
Output
4.627909672957581
max() Function Example:
import math
print(math.ceil(-46.5))
Output
-46
ceil() Function Example:
print(max(10,489,52))
Output
489
min() Function Example:
print(min(-5,3,-60))
Output
-60
modf() Function Example:
import math
print(math.modf(102.36))
Output
(0.35999999999999943, 102.0)
pow() Function Example:
import math
print(math.pow(5,3))
Output
125.0
round() Function Example:
print(round(-65.82125,2))
Output
-65.82
sqrt() Function Example:
import math
print(math.sqrt(64))
Output
8.0
2) Random Number Functions
Python supports the following random number functions used in games, simulations, testing, security, and privacy applications. To use these functions, we need to import a random module.
Note: We run these functions multiple times in our program, then these functions will give different outputs every time.
- choice(seq) : It returns a random element from a sequence as a list, tuple, or string.
- randrange ([start,] stop [,step]) : It returns a randomly selected element from range(start, stop, step), where Start <= r < Stop.
- random() : It returns a random float “r”, such that r-value is as 0 < = r and r < 1.
- randint (low, high) : It returns an integer random number in between the given low and high values or equal to a low and high value ( low=< r = < high).
- shuffle(list) : It randomizes the list of elements in place, which is passed inside this function.
- seed([x]) : It sets the integer starting value for generating random numbers. We have to call this function before calling any other random module function. In this function, x is the seed for the next random number. It takes the system time to generate the next random number if omitted.
- uniform(lower limit, upper limit) : It returns a random float r, such that lower limit < = r and r < upper limit. It works the same as randint (low, high).
Now let’s take quick examples of each random function in the list above.
choice() Function Example:
import random
print(random.choice(['python','.net','ruby']))
print(random.choice((0, -1 ,5)))
Output
Ruby
0
randrange() Function Example:
import random
print("random number with stop range=199 : ",random.randrange(199))
print("random number with range (-2,5) : ",random.randrange(-2,5))
Output
random number with stop range=199 : 118
random number with range (-2,5) : 0
random() Function Example:
import random
print("random number1: ",random.random())
print("random number2: ",random.random())
Output
random number1: 0.7506857721524778
random number2: 0.010993461964750928
randint() Function Example:
import random
a=0
while (a < 6):
r=random.randint(0,6)
print (r)
a= a+1
Output
2
5
3
4
5
2
shuffle() Function Example:
import random
alphabet=['a','b','c','d']
random.shuffle(alphabet)
print("Reshuffled list alphabet: ",alphabet)
Output
Reshuffled list alphabet: [‘a’, ‘d’, ‘b’, ‘c’]
seed() Function Example:
import random
random.seed(5)
print("Random number 1 with seed 5: ", random.random())
Output
Random number 1 with seed 5: 0.6229016948897019
uniform() Function Example:
import random
print("Random float between 2 to 6 is ", random.uniform(2,6))
Output
Random float between 2 to 6 is 4.967147957042918
3)Trigonometric Functions
Python supports the following Trigonometry functions, which perform Trigonometry calculations. To use these functions, we need to import the math module.
Function | Description |
---|---|
acos(x) | It returns the arc cosine of x in radians. |
asin(x) | It returns the arc sine of x in radians. |
atan(x) | It returns the arc tangent of x in radians. |
atan2(y, x) | It returns atan(y / x), in radians. |
cos(x) | It returns the cosine of x radians. |
hypot(x,y) | It returns the euclidean norm, sqrt(x*x + y*y). |
sin(x) | It returns the sine of x radians. |
tan(x) | It returns the tangent of x radians. |
degrees(x) | It converts angle x from radians to degrees. |
radians(x) | It converts angle x from degrees to radians. |
Now let’s take quick examples of each trigonometric function in the list above.
acos() Function Example:
import math
print(math.acos(0.64))
Output
0.8762980611683406
asin() Function Example:
import math
print(math.asin(0.64))
Output
0.694498265626556
atan() Function Example:
import math
print(math.atan(0.64))
Output
0.5693131911006619
atan2() Function Example:
import math
print(math.atan2(10,20))
Output
0.4636476090008061
cos() Function Example:
import math
print(math.cos(-3))
Output
-0.9899924966004454
hypot() Function Example:
import math
print(math.hypot(3,2))
Output
3.605551275463989
sin() Function Example:
import math
print(math.sin(3))
Output
0.1411200080598672
tan() Function Example:
import math
print(math.tan(4))
Output
1.1578212823495777
degrees() Function Example:
import random
print(math.degrees(4))
Output
229.1831180523293
radians() Function Example:
import random
print(math.radians(4))
Output
0.06981317007977318
4) Mathematical Constants
A constant is a type of variable whose value can’t be changed. They are usually declared in a module where a module is a file that can contain variables, functions, etc., which is imported to the main file.
Python supports two mathematical constants as below. To use them, we need to import the math module.
Constants | Description |
---|---|
pi | The mathematical constant pi. |
e | The mathematical constant e. |
Conclusion
In this article, we have learned what a number object is in Python and what are the different types of functions that are used with numbers, and how to generate a random number in different ways
Python Tutorials List:
- Python Tutorials list: access all python tutorials.