Numbers in Python

FREE Online Courses: Dive into Knowledge for Free. Learn More!

We deal with numbers in many situations. They play an important role in different fields. We will learn about numbers in Python and the different operations which we can play with them.

So, let’s start with the data type that categorizes these numbers.

Python Numeric Data type

Numbers in Python come under the category of Numeric data types. Because of the dynamic nature of Python, we don’t need to declare any data type. We can classify these numbers into three types:

a. Integers (int)
b. Decimals (float)
c. Complex numbers (complex)

The following example shows the creation of each of these types.

Example of different types of numeric data types:

a= 5 #int datatype
b=4.5 #float datatype
c=9+2j #complex datatype

print("The type of the value ",a ,"is:",type(a))
print("The type of the value ",b ,"is:",type(b))
print("The type of the value ",c ,"is:",type(c))

Output:

The type of the value 5 is: <class ‘int’>
The type of the value 4.5 is: <class ‘float’>
The type of the value (9+2j) is: <class ‘complex’>

We have created the three numeric data types and checked the type using the built-in function ‘type()’. You can also check the data type using another built-in function called isinstance(), which takes the value and the datatype as inputs. This function gives True if the value belongs to the data type, else False.

Example of checking data type with isinstance() :

complex_1= 7+8j
print(isinstance(complex_1,complex)) #checking if the value is complex or not

Output:

True

Let us discuss all these types in detail in further sections.

Int Data type in Python

The integer data type includes all the whole numbers, positive or negative, without any decimal point. The number can be of any length.

Example of integers:

num1=-56
num2=99999999999999999
type(num1)
type(num2)

Output:

<class ‘int’>
<class ‘int’>

There is another way to check if a number belongs to a particular data type. This is by using a built-in function ‘isinstance()’

Example of checking data type using ‘isinstance()’ function:

num=4589
isinstance(num,int)

Output:

True

Operations on integers in Python:

Now let’s discuss some operations on integers using coding:

Example of operations on integers:

num1=8
num2=-2
print("Sum=",num1+num2)
print("Subtraction=",num1-num2)
print("Multiplication=",num1*num2)
print("Division=",num1/num2)
print("Integer division=",num1//num2)
print("Modulus=",num1%num2)
print("Power=",num1**(-num2))

Output:

Sum= 6
Subtraction= 10
Multiplication= -16
Division= -4.0
Integer division= -4
Modulus= 0
Power= 64

All the operations are the same as the ones we see in math. Observe that on division we got the result as a decimal number, but on using the ‘//’ operator, called the integer division operator we got an integer as a result.

Different ways to create integers in Python:

Now let us discuss some other interesting things regarding the creation of integers:
a. We know that we must not use commas while creating an integer in Python. However, we are allowed to use underscores.

Example of creating an integer with underscores:

num=1_234_345
print(num)

Output:

1234345

b. While creating an integer, we are not allowed to use 0 as the leftmost digit. This gives an error.

Example on getting an error on using 0 as the most significant digit:

num=0123

Output:

SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

Float Data type in Python

Float data type represents all the real numbers. All the numbers belonging to the float data type have decimal points. There are different ways in which we can obtain float values. Let us start with the basic one.

Example of creating float data types:

dec_num1=4.67
dec_num2=-56.90
print("The type of the value ",dec_num1 ,"is:",type(dec_num1))
print("The type of the value ",dec_num2 ,"is:",type(dec_num2))

Output:

The type of the value 4.67 is: <class ‘float’>
The type of the value -56.9 is: <class ‘float’>

Using e/E to create float:

You can use underscores here also between the digits. Another way to create float value is to use exponent ‘e’ or ‘E’. Here the number preceding e/E is multiplied with the 10 to the power of the number after e/E.
For example, xEy represent x*(10y). The number y can be a positive or negative integer. Below example shows some results.

Example of creating float value using ‘e’ or ‘E’:

num1=34e2
num2=-9E3
num3=5.43567e2
num4=34_456.189_43

print("The type of the value ",num1 ,"is:",type(num1))
print("The type of the value ",num2 ,"is:",type(num2))
print("The type of the value ",num3 ,"is:",type(num3))
print("The type of the value ",num4 ,"is:",type(num4))

Output:

The type of the value 3400.0 is: <class ‘float’>
The type of the value -9000.0 is: <class ‘float’>
The type of the value 543.567 is: <class ‘float’>
The type of the value 34456.18943 is: <class ‘float’>

Other ways of getting a float value in Python

Other cases where we get float is while doing operations like:

a. Addition

We get a float value when we add an integer and float. For example,

Example of getting a float value on addition:

num=1+3.4
>>> print("The type of the value ",num ,"is:",type(num))

Output:

The type of the value 4.4 is: <class ‘float’>

Here 1 will be considered as 1.0 while adding 3.4, and the result is 4.4.

b. Dividing

When we divide an integer or a float by an integer/float using the ‘/’ operator, we get a float value.

Example of getting a float value on dividing:

num=18/4
print("The type of the value ",num ,"is:",type(num))

Output:

The type of the value 4.5 is: <class ‘float’>
c. Multiplying an integer by float:

We get a float value when we multiply an integer/ a float value by a float value.

Example of getting a float value on multiplying integer by decimal value:

num=12*3.4
print("The type of the value nume:",num ," and its type is:",type(num))

Output:

The type of the value nume: 40.8 and its type is: <class ‘float’>

Another important point to note is that float accepts only 15 digits after the decimal point. After this, it rounds off. Look at the below example.

Example of rounding off property after reaching 15 digits after the decimal:

num=8.111111111111119
print(num)

Output:

8.11111111111112

Operations on float values in Python:

Similar to operations on integers we can do all the operations on floats. Let us look at some of them-.

Example of operations on Python float:

num1=3.2
num2=4.1
print("Sum=",num1+num2)
print("Subtraction=",num1-num2)
print("Multiplication=",num1*num2)
print("Division=",num1/num2)

Output:

Sum= 7.3
Subtraction= -0.8999999999999995
Multiplication= 13.12
Division= 0.7804878048780489

We can see that the value of subtraction is not the expected result. It is called floating-point representation error and occurs due to the way float values are stored in the memory.

Use of Decimal module in Python

To solve the above problem, we can use the decimal module in Python. This module is mainly used while doing operations on values with a decimal point. We use this module when we want exact decimal values with controlled precision to specific decimal places.

Example of using decimal module to do calculations:

from decimal import Decimal as D
print(D('3.2') - D('4.1'))

Output:

-0.9

Complex Data type in Python

Complex data type includes the numbers with a real and an imaginary part and is of form a+bj. Here a represents the real coefficient and b is the imaginary coefficient. Let us see some examples.

Examples of creation of Python complex numbers:

complex_no= 2+7j
complex_no2=3j

print("The type of the value ",complex_no ,"is:",type(complex_no))
print("The type of the value ",complex_no2 ,"is:",type(complex_no2))

Output:

The type of the value (2+7j) is: <class ‘complex’>
The type of the value 3j is: <class ‘complex’>

Wrong ways of creating Python complex numbers:

We can only use ‘j’ or ‘J’ and not ‘i’. Also, we should give the coefficient for the imaginary part else it will give an error. Let us see these cases.

1. Examples of getting an error by wrong creation of complex numbers:

c_no1=12+9i

Output:

SyntaxError: invalid syntax

2. Examples of getting an error by wrong creation of complex numbers:

c_no1=3+j

Output:

Traceback (most recent call last):
File “<pyshell#71>”, line 1, in <module>
c_no1=3+j
NameError: name ‘j’ is not defined

Operations on Complex Numbers in Python:

We can apply the operators on complex numbers too. Below example shows these operations.
Example of operations on complex numbers:

comp1=4+7j
comp2=5-9j
print("Sum=",comp1+comp2)
print("Subtraction=",comp1-comp2)
print("Multiplication=",comp1*comp2)
print("Division=",comp1/comp2)
print("Multiplying with scalar=", comp1*3)
print("Dividing by scalar=" ,comp1/3)
print("Exponent=" ,comp1**2)

Output:

Sum= (9-2j)
Subtraction= (-1+16j)
Multiplication= (83-1j)
Division= (-0.40566037735849053+0.6698113207547169j)
Multiplying with scalar= (12+21j)
Dividing by scalar= (1.3333333333333333+2.3333333333333335j)
Exponent= (-33+56j)

Binary, Octal, and Hexadecimal Numbers in Python

Other than the above data types, there are other forms of numbers to represent integers. These differ from each other by the base of the systems. These are:

1. Binary Numbers in Python

These are the numbers with base 2, with numbers as a combination of 0s and 1s. These numbers are prefixed with 0b or 0B. Let us see some examples of the creation of binary numbers.

Example of Python binary numbers:

bin_no1=0b1101
print(bin_no1)
print("The type of the value ",bin_no1 ,"is:",type(bin_no1))

bin_no2=0b_101_100
print(bin_no2)
print("The type of the value ",bin_no2 ,"is:",type(bin_no2))

Output:

13
The type of the value 13 is: <class ‘int’>44
The type of the value 44 is: <class ‘int’>

2. Octal Numbers in Python

These are the numbers with base 8 and prefixed with 0O or 0o. These contain digits from 0 to 7 only. If you use 8,9 then it gives an error. The below example gives an understanding of it.

Example of Python octal numbers:

oct_no1=0o345
print(oct_no1)
print("The type of the value ",oct_no1 ,"is:",type(oct_no1))

oct_no2=0o486

Output:

229
The type of the value 229 is: <class ‘int’>
SyntaxError: invalid digit ‘8’ in octal literal

3. Hexadecimal Numbers in Python

These are the numbers with base 16 and have 0x or 0X. This system has digits from 0-9 and A-F to represent 10 to 15. Let us see an example of creating a hexadecimal number.

Example of Python hexadecimal numbers:

hex_no1=0x34
print(hex_no1)
print("The type of the value ",hex_no1 ,"is:",type(hex_no1))

hex_no2=0xAF
print(hex_no2)
print("The type of the value ",hex_no2,"is:",type(hex_no2))

Output:

52
The type of the value 52 is: <class ‘int’>
175
The type of the value 175 is: <class ‘int’>

Conversions from one numeric type to other in Python

We might come across cases when we have to convert from one form to another. This is done using the following built-in functions:

1. int(): This is used to convert into the integer data type. Let us look at some examples.

Example of converting float to integer in Python

a=int(18.4)
print("The type of the value ",a,"is:",type(a))

Output:

The type of the value 18 is: <class ‘int’>

Example of converting binary, octal and hexadecimal to integer in Python

num1=int(0b10101)
num2=int(0o453)
num3=int(0x12AB)
print("The type of the value ",num1,"is:",type(num1))
print("The type of the value ",num2,"is:",type(num2))
print("The type of the value ",num3,"is:",type(num3))

Output:

The type of the value 21 is: <class ‘int’>
The type of the value 299 is: <class ‘int’>
The type of the value 4779 is: <class ‘int’>

However, we get an error if we try this conversion on complex numbers.

Example of getting error for converting complex to integer in Python

num=int(3+7j)

Output:

Traceback (most recent call last):
File “<pyshell#113>”, line 1, in <module>
num=int(3+7j)
TypeError: can’t convert complex to int

2. float(): This Function is used to convert to float values. Let us look at some examples.

Example of converting integer to float in Python

num=float(5)
print("The type of the value ",num,"is:",type(num))

Output:

The type of the value 5.0 is: <class ‘float’>

Example of converting binary, octal and hexadecimal to float in Python

num1=float(0b1001)
num2=float(0o307)
num3=float(0x15E)
print("The type of the value ",num1,"is:",type(num1))
print("The type of the value ",num2,"is:",type(num2))
print("The type of the value ",num3,"is:",type(num3))

Output:

The type of the value 9.0 is: <class ‘float’>
The type of the value 199.0 is: <class ‘float’>
The type of the value 350.0 is: <class ‘float’>

Similar to int(), we get an error with float() too if we try on complex numbers.

Example on getting error for converting complex to float:

num=float(9-6j)

Output:

Traceback (most recent call last):
File “<pyshell#123>”, line 1, in <module>
num=float(9-6j)
TypeError: can’t convert complex to float

3. Python complex(): This converts the numbers to complex form. Let us see some examples.

Example of converting Numbers to complex in Python

num1=complex(4)
num2=complex(7.6)
num3=complex(4+7.0j)

print("The type of the value ",num1,"is:",type(num1))
print("The type of the value ",num2,"is:",type(num2))
print("The type of the value ",num3,"is:",type(num3))

Output:

The type of the value (4+0j) is: <class ‘complex’>
The type of the value (7.6+0j) is: <class ‘complex’>
The type of the value (4+7j) is: <class ‘complex’>

We can give two arguments to the complex() type conversion function. It considers the first value as the real part and the second value as the imaginary part. For example,

Example of converting Number to complex in Python

no1=complex(2,5)
print("The type of the value ",no1,"is:",type(no1))

no2=complex(3.4,7.9)
print("The type of the value ",no2,"is:",type(no2))

Output:

The type of the value (2+5j) is: <class ‘complex’>

The type of the value (3.4+7.9j) is: <class ‘complex’>

4. bin(): This is used to convert integers to binary form. This does not work on float and complex values.

Example of converting Integer to binary in Python

num1=bin(9)
print(num1)

num2=bin(5.8)

num3=bin(1+5j)

Output:

0b1001

Traceback (most recent call last):
File “<pyshell#126>”, line 1, in <module>
num2=bin(5.8)
TypeError: ‘float’ object cannot be interpreted as an integer

Traceback (most recent call last):
File “<pyshell#127>”, line 1, in <module>
num3=bin(1+5j)
TypeError: ‘complex’ object cannot be interpreted as an integer

5. oct(): This converts the numbers to the octal system. Even this works only on integers.

Example of converting Number to octal in python

num1=oct(11)
print("The type of the value ",num1,"is:",type(num1))

num2=oct(3.6)

num3=oct(6+9j)

Output:

The type of the value 0o13 is: <class ‘str’>

Traceback (most recent call last):
File “<pyshell#136>”, line 1, in <module>
num2=oct(3.6)
TypeError: ‘float’ object cannot be interpreted as an integer

Traceback (most recent call last):
File “<pyshell#138>”, line 1, in <module>
num3=oct(6+9j)
TypeError: ‘complex’ object cannot be interpreted as an integer

6. hex(): This converts the integers into hexadecimal form. However, we get errors when applying with the float or complex values. For example,

Example of converting Integer to octal in Python

num1=hex(34)
print("The type of the value ",num1,"is:",type(num1))

num2=hex(7.1)

num2=hex(5+7j)

Output:

The type of the value 0x22 is: <class ‘str’>

Traceback (most recent call last):
File “<pyshell#141>”, line 1, in <module>
num2=hex(7.1)
TypeError: ‘float’ object cannot be interpreted as an integer

Traceback (most recent call last):
File “<pyshell#142>”, line 1, in <module>
num2=hex(5+7j)
TypeError: ‘complex’ object cannot be interpreted as an integer

Math, Fractions, and Random Modules in Python

We know that Python has a wide range of modules. Let us discuss some modules that are concerned with the numbers.

1. Math Module in Python: This module has important functions like absolute, exponential, square root, sine, etc. Some of them are:

a. abs(x), fabs(x): Gives the absolute value of x (x if x>0, -x if x<0, and 0 if x=0)
b. sqrt(x): Returns the square root of x
c. ceil(x): Returns the lowest integer greater than or equal to x
d. floor(x): Returns the largest integer less than or equal to x
e. exp(x): Returns the exponential of x (e^x)
f. log(x): This function works as a natural logarithm of x
g. log10(x): This function works as a logarithm of x with the base of 10
h. round(x,n): Rounds the value of x to n decimal values. If ‘n’ is not mentioned, it rounds to one decimal point.
i. pow(x,y): Computes the value of x to the power y and returns the result
j. modf(x): It splits the integer and the decimal parts and returns them as elements of a tuple.
k. min(x1, x2, …) : Returns the minimum value of the arguments
l. max(x1, x2, …): Returns the maximum value of the arguments

Trigonometric Functions in Python

a. sin(x): Computes the sine of x, considering x as a radian value, and returns the result.
b. cos(x): Computes the cosine of x, considering x as a radian value, and returns the result.
c. tan(x): Computes the tangent of x, considering x as a radian value, and returns the result.
d. asine(x): Computes the inverse sine of x and returns the radian value.
e. acos(x): Computes the inverse cosine of x and returns the radian value.
f. atan(x): Computes the inverse tangent of x and returns the radian value.
g. atan2(y,x): Computes the inverse tangent of y/x, and returns the radian value.
h. hypot(x,y): Computes the hypotenuse value considering x and y as sides of right angle triangle and returns the result
i. degrees (x): Computes the degree value of the angle given in radians
j. radians(x): Computes the radians value of the x, which is in degrees

It also holds the common math constant:

a. pi: The mathematical value of around 3.141
b. e: The mathematical constant of value around 2.718

Let us see some examples of using functions in this module.

Example of using functions in math module in Python:

import math
print(math.sqrt(9))

print(math.exp(5))

print(math.cos(90))

Output:

3.0

148.4131591025766

-0.4480736161291701

2. Fractions module in Python: This module returns the values in numerator/denominator form. Let us look at some examples.

Example of getting fractional form using fractions module in Python

from fractions import Fraction
print(Fraction(1.25))

print(Fraction(19,5))

Output:

5/4

19/5

This module supports all the operations that can be done on numbers. Let us discuss some examples,

Example of doing operations using fractions module in Python

from fractions import Fraction
print(Fraction(1,2)+Fraction(3,2))

print(1/Fraction(3,4))

print(Fraction(2,3)*Fraction(3,4))
print(Fraction(7,3)>Fraction(8,3))

Output:

2

4/3

1/2

False

3. Random Module in Python: This module is used to generate a random value in the given range. This is very useful in some situations like building a dice game.

Example of generating random numbers in Python

import random
print(random.randrange(1, 10)) #print random integer from 1 to 10, 10 excluded

print(random.random())#print random value between 0 and 1

Output:

3
0.14719095324182307

In the randrange we can also give a third argument called step that decides the incrementation in between by using the randrange multiple times. We can also use this random module of lists to get a random value from the list and to shuffle the list randomly.

Example of using Python random module on lists:

list1=[1,2,3,4,5,6,7,8]
print(random.choice(list1)) #print random value from the list
3
random.shuffle(list1) #shuffling a list in a random way
print(list1)

Output:

3

[6, 2, 4, 8, 1, 5, 7, 3]

Other common functions in the module are:

a. seed([x]): It is used to fix the random state for a random function. So, when this random function is called again in the program, it returns the same value.

b. uniform(x,y): It returns a random value between x and y, y exclusive and x inclusive.

Python Interview Questions on Numbers

After learning a lot of concepts on numbers, let us practice some interview questions.

Q1. Store the number 0.00156 in a variable in exponent form and find its fractional value

Ans 1. Example of calculating area of circle in Python

num=156e-5
print(num)
from fractions import Fraction
print(Fraction(num))

Output:

0.00156
7194230188746725/4611686018427387904

Q2. Show the sum of 7.1 and 3.3 obtained by normal addition and using the decimal module.

Ans 2. Below is an example of showing the difference between decimal and float in Python

print(7.1+3.3)

from decimal import Decimal as D
print(D('37.1') - D('3.3'))

Output:

10.399999999999999

33.8

Q3. Print the smallest integer greater than and the largest integer less than 347.89.

Ans 3. We can use ceil() and floor() functions in the math module to print the integers.

import math
num= 347.89
print("The smallest integer greater than ",num,"is:",math.ceil(num))
print("The largest integer less than ",num,"is:",math.floor(num))

Output:

The smallest integer greater than 347.89 is: 348
The largest integer less than 347.89 is: 347

Q4. Let a game that gives random values from 1 to 100. Assume two friends play this game. The one who gets the highest number wins the game. Then find the winner and also by what score.

Ans 4. Below are example of random module in Python

import random
person1=random.randrange(1, 100)
person2=random.randrange(1, 100)
if(person1>person2):
  print("The first person is the winner by ", person1-person2)
elif(person1<person2):
  print("The second person is the winner by ",person2-person1)
else:
  print("It is a tie!")

Output:

The second person is the winner by 61

Q5. Calculate the area of a circle of radius 6.5. Use pi from the math module.

Ans5. Example of calculating the area of a circle in Python:

import math
area=math.pi * 6.5**2
print(area)

Output:

132.73228961416876

Quiz on Numbers in Python

Conclusion

Hence, we have learned different types of numbers in Python and their operations. We also saw different systems of integers like binary and octal. Then we discussed conversions from one number form to another.

We also saw different modules related to numbers and some examples. Finally, we practiced using some interview questions on numbers.

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *