PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python Numbers

Python Numbers

Updated on: March 18, 2021 | 2 Comments

Python offers a wide variety of inbuilt data types to handle different requirements. Each data type comes with built-in methods for performing different operations.

The numeric data in Python is generally in three formats namely Integer, Float, and Complex.

In this article, you will learn the basic numeric data types available in Python, along with the different ways of creating them.

You will also learn the different methods available to carry out the basic operations in them and the Math module and the Python Decimal and Fraction modules in detail.

Table of contents

  • Integer Number
  • Float Number
  • Complex Numbers
  • Hexadecimal and Octal Numbers
  • Number Type Conversion
    • Implicit Type Conversion
    • Explicit Type Conversion
  • Math Module Methods to work with Numerical Data
    • ceil() and floor()
    • degrees() and radians()
    • sin() and cos()
    • factorial()
    • fabs() and trunc()
    • pow() and log()
  • Checking Functions
    • isfinite() and isinf()
    • isnan()
    • isclose()
    • Square root, GCD, Power, and Exponentials of a Number
  • Other Python Number Methods
    • bit_length()
    • to_bytes()
    • is_integer()
    • as_integer_ratio()
  • Python Decimal Module
    • Creating a Decimal Number
    • Decimal Methods
      • getcontext()
    • Mathematical Operations
  • Python Fraction Module
    • Fraction Module Methods
      • limit_denominator()
      • from_float()
      • ceil() and floor()
  • Printing Numbers in different Formats
  • Summary of all the Methods
  • Related Tutorials

Integer Number

Int or Integer data type is used for numeric data of any length without a decimal point. Integer data can be either positive or negative.

For example, we can use the int data type to store the roll number of a student. The Integer type in Python is represented using a int class.

We can create an integer variable using the two ways

  1. Directly assigning an integer value to a variable
  2. Using a int() class.

Example to create Integer number

roll_no = 33
# display roll no
print("Roll number is:", roll_no)  # 33
print(type(roll_no))  # class 'int'

# create integer using int() class
id = int(25)
print(id)  # 25
print(type(id))  # class 'int'

Float Number

Float or Floating point data type is used for numeric data with one or more decimals. It can be either positive or negative.

We can create a Integer or Float variable by assigning values. We can get the type of a variable by using the type function.

#data types
x=-9999
y=99.99
print(type(x))
print(type(y))

Output

<class 'int'>
 <class 'float'>

Complex Numbers

A Python complex number is one having a real and imaginary parts. It is generally represented as

c==c.real+c.imaginary*1j

This is the rectangular or cartesian representation of the complex number where z.real and z.imaginary are the cartesian coordinates.

A Python complex number can be represented in both rectangular as well as polar coordinates. Polar coordinates are one alternative way of representing complex numbers that will have r and phi where r is the modulus and phi is the phase angle.

Python provides a separate module called cmath with functions, especially for these complex numbers.

In addition to the regular trigonometric and classification functions, it has additional methods to perform the conversion from rectangular to polar and to find the phase angles.

import cmath

#to find the phase angle
phi = cmath.phase(complex(-1.0, 1.0))
print(phi)

#to find the rectangular coordinates
c=cmath.rect(1,2)
print("real::",c.real)
print("imaginary::",c.imag)
print("complex number::",c)

#print the polar coordinates
p=cmath.polar(c)
print("polar::",p)

Output

2.356194490192345
real:: -0.4161468365471424
imaginary:: 0.9092974268256817
complex number:: (-0.4161468365471424+0.9092974268256817j)
polar:: (1.0, 2.0)

As seen in the above output we can find the real and imaginary part of the complex number and convert it from rectangular to polar and vice versa.

Hexadecimal and Octal Numbers

We can represent a number in Octal form by preceding with a 0 and in hexadecimal form by preceding with a 0x. We can convert a number from integer to octal by using the oct() method and into hexadecimal form by using the hex() method.

i = 10
print("in octal form::", oct(i))
print("in hexa decimal form ::", hex(i))

Output

in octal form:: 0o12
in hexa decimal form :: 0xa

Number Type Conversion

Python allows the conversion of data from one type to another in two ways.

  • Implicit type conversion
  • Explicit type conversion

Implicit Type Conversion

In the case of two compatible data types, Python performs the type conversion implicitly. Compatible data types are in general two numeric data types like int and float. It will convert the smaller data type to larger one to prevent any data loss. For eg.; int data will be converted to float.

But, if we try to perform some operations between a string and int types then it will throw Type error.

Let us see this with an example.

x = 99
y = 1.111

#data in int and float
print(type(x))
print(type(y))

#addition
z = x+y

#type after addition
print(type(z))

Output

<class 'int'>
<class 'float'>
<class 'float'>

Explicit Type Conversion

We can convert data in one type to another explicitly using int(), float(), complex() etc; This is called typecasting.

#concatenating int and str types
i = 99
s = "apple"
print(s+str(i))

Output

apple99

Math Module Methods to work with Numerical Data

Python has built-in methods to perform complex mathematical operations.

In order to use them, we need to import the math module using the import math statement. We will see some most widely used math methods with examples.

ceil() and floor()

These two methods are used to round a float number to the nearest integer. As the name suggests, ceil()  method is used to round the number UP to the nearest integer value while floor() is used to round a number DOWN to the nearest integer value.

import math as m

a = 1.4
print(m.ceil(a))
print(m.floor(a))

Output

2
1

degrees() and radians()

In trigonometric calculations, we represent angles in both degrees as well as radian’s form.

We use the degrees() method to convert the angle in radians to degrees.
Similarly, we use radians() method to convert the angle in degrees to radians.

In addition to the above methods, math module also provides some frequently used constants like pi. Let us see this with an example below.

import math

pi = math.pi
print(pi)
#To find the degree equivalent of the radians
print("Degree value of pi is ::",math.degrees(pi))

#Radians for the degrees
print("Radian value of 90 degree is ::",math.radians(90))

Output

3.141592653589793
Degree value of pi is :: 180.0
Radian value of 90 degree is :: 1.5707963267948966

sin() and cos()

We can find the trigonometric sin and cos values using built-in methods in the python math module.

We can find the sin value of an angle in radians using the sin() method. Similarly, we can find the cos value of the angle in radians using the cos() method.

#sin value of 90
radians_90=math.radians(90)
print("sin value of pi/2 is ::", math.sin(radians_90))

#cos value of 60
radians_60 = math.radians(60)
print("cos value of pi/2 is ::", math.cos(radians_60))

Output

sin value of pi/2 is :: 1.0
cos value of pi/2 is :: 0.5000000000000001

factorial()

We can find the factorial of any positive integer using the <code>factorial()</code> method in the math module. This method will return the factorial value, multiplication of all the numbers from the specified number until 1. E.g., the factorial of 5 is 5*4*3*2*1. Let us see this with an example.

import math

#factorial of 6 : 6*5*4*3*2*1
print("factorial of 6 is ::", math.factorial(6))

Output

factorial of 6 is :: 720

fabs() and trunc()

We can use the fabs() method in the math module to find a number’s absolute value as a float. This method will remove the negative sign, if any, and return only the absolute float value.

We can truncate a number to its nearest integer using the trunc() method. This method will not return the negative sign, if any.

import math

#floating absolute value
print("floating absolute value::", math.fabs(-99.999))
print("floating absolute value of an integer::", math.fabs(-11))

#truncated integer value
print("truncated integer value::", math.trunc(-99.99))

Output

floating absolute value:: 99.999
floating absolute value of an integer:: 11.0
truncated integer value:: -99

As we can see the fabs() method is returning the floating absolute value of both a float number as well as an integer. The trunc() method returns the truncated integer value of the given number which includes the negative sign as well.

pow() and log()

We can find the natural log value of a number using the log() method in math module.
The pow() method accepts two arguments, x, and y, and returns the value of x raised to power y. Let us see both the methods with an example.

import math

print("The value of 9^3 is ::", math.pow(9, 3))
print("The log value of 5::", math.log(5))

Output

The value of 9^3 is :: 729.0
The log value of 5:: 1.6094379124341003

Checking Functions

In math module, there are methods to check whether a number is either finite or infinite. We also have a method to check whether an argument is number or not.

isfinite() and isinf()

We can check whether a number is finite or not using the isfinite() method. This method will return True if the value is finite and false if it is infinite. In the same way, we can check whether a number is infinite or not using the isinf() method.

#checking whether a number is finite or not
print("Finite or not::",math.isfinite(-0.00006))
#checking whether a number is infinite or not
print("Infinite or not::",math.isinf(math.inf))

Output

Finite or not:: True
Infinite or not:: True

isnan()

We can also check whether the argument we pass is a number or not using the isnan() method.This method will return true the passed argument is not a number.

#checking whether it is a number or not
print("IS a number or not::", math.isnan(math.nan))

Output

IS a number or not:: True

isclose()

We can find whether two numbers are close or not using the isclose() method. We can even mention the absolute tolerance which will compare the numbers near 0 and it is the minimum tolerance. We can pass the relative tolerance which is the maximum difference allowed between two numbers.

#compare the closeness of two values
print("with absolute tolerance  difference::", math.isclose(1.5, 2.05, abs_tol = 0.55))

print("with relative difference < difference::", math.isclose(1.5,1.75,rel_tol=0.5))

Output

with absolute tolerance  difference:: True
with relative difference < difference:: True

Square root, GCD, Power, and Exponentials of a Number

In addition to the above methods, there are methods that are commonly used like

  • sqrt(): For finding the square root,
  • gcd(): For finding the greatest common divisor,
  • pow(x,y): For finding  number x raised to power y and
  • exp(x): exponentials of number x

Let us see one simple example for all the above functions.

#finding sqrt
print("The square root of 25 is ::", math.sqrt(25))
print("The square root of 10 is ::", math.sqrt(10))

#Greatest Common Divisor
print("The greatest common divisor is ::", math.gcd(6,12))

#exponential value
print("The value os e(x) is::", math.exp(-2))

#Number raised to power
print("The value of 9^3 is ::", math.pow(9, 3))

Output

The square root of 25 is :: 5.0
The square root of 10 is :: 3.1622776601683795
The greatest common divisor is :: 6
The value os e(x) is:: 0.1353352832366127
The value of 9^3 is :: 729.0

Other Python Number Methods

In addition to the above methods, there are few methods in Python for performing some number-related operations. Let us see each with a small example.

bit_length()

This method is used to find the number of bits to represent a number in binary format excluding the sign and leading zeros.

i=-99
print("bit length::", i.bit_length())

#checking by printing the binary version
bin(i)

Output

bit length:: 7
-0b1100011

to_bytes()

This method will return an array of bytes to represent an integer.

(24).to_bytes(3, byteorder='big')

Output

b'\x00\x00\x18'

The above output shows the array of bytes to represent the integer value 24. The byteorder argument determines the byte order used to represent the integer. In case the  byteorder is “big”, the most significant byte is at the beginning of the byte array. In case the  byteorder is “little”, the most significant byte is at the end of the byte array. The integer is represented using length bytes. If the integer cannot be represented within that length then we will get Overflow error.

is_integer()

We can check whether the given number is an integer or not using the is_integer() method. It will return a boolean value.

f=0.25

f.is_integer()

Output

False

As seen in the above example the value of f is not an integer and we got the output as False.

as_integer_ratio()

We can represent the floating number as an integer number ratio. In case of not a perfect fraction ,then the nearest possible ratio will be returned.

f=0.25
f.as_integer_ratio()

Output

(1, 4)

Python Decimal Module

Python stores a decimal value internally as a base 2 binary fractions. For e.g 1/3 in base 10 can be stored as  0.3, 0.33, or 0.3333. But we can add as many digits in the end as possible to get to the near possible approximation.

Due to the limitations of the floating-point arithmetic some decimal numbers cannot be represented exactly in base 2 binary fractions.

To prevent some data loss while performing mathematical operations, especially in numbers with decimal digits, Python provides a separate module, ‘Decimal.’

Creating a Decimal Number

With the help of the decimal  module we can actually set the precision of the number to be displayed up to 28 digits. Based on the requirements we can actually specify the amount of precision while representing the decimal numbers.

  • Using decimal() constructor: We need to import the decimal module to perform the following operations.
  • Passing a tuple inside the decimal() constructor: Tuple will have three-part. The first part will be 0 for positive and 1 for negative. The second part will be the Integer component.

We can even set flags like ROUND_CEILING,ROUND_FLOOR,ROUND_UP,ROUND_DOWN and traps to raise a Python exception during conditions like Division by Zero.By default certain conditions like the division by zero are set to true only.

import decimal
from decimal import *

print(Decimal(0.01))
print(Decimal('0.05'))
print(Decimal((1, (9,9,9,9), -2)))

Output

0.01000000000000000020816681711721685132943093776702880859375
0.05
-99.99

Decimal Methods

getcontext()

We can set the precision using the getcontext() method and even set the flags to mention whether we need to round the digits up or Down.

print(Decimal(3) / Decimal(77))

Output

0.03896103896103896103896103896

We can limit the number of digits in the above output by setting the precision using the getcontext().

getcontext().prec = 2
getcontext().rounding = decimal.ROUND_UP
 
print(Decimal(3) / Decimal(77))

Output

0.039

Mathematical Operations

In addition to this, we have the flexibility of using all the mathematical functions like sqrt,log , etc; available in the decimal module as well.

Note: It is very important to clear_flags() which we have already set in order to adjust our precision differently for different requirements.

import decimal
from decimal import Decimal, getcontext
getcontext().clear_flags()
print(Decimal(2).sqrt())

Output

1.414213562373095048801688724

Python Fraction Module

Python provides a separate module for handling the rational numbers called Fraction Module.

A fraction can be formed from a decimal , float, integers ,another rational number or a string.Let us see each one with a small example. We have to import the fractions module first.

from fractions import Fraction

Let us see examples for each of the above.

from fractions import Fraction
#From two integers
Fraction(25, -100)
#From another fraction
Fraction(' -3/7 ')
#from a decimal
from decimal import Decimal
Fraction(Decimal('9.9'))
#from a decimal without quotes
from decimal import Decimal
Fraction(9.1)
#Empty Fraction
Fraction()

Output

Fraction(-1, 4)
Fraction(-3, 7)
Fraction(99, 10)
Fraction(9.1)
Fraction(0, 1)

Fraction Module Methods

limit_denominator()

Some fractions are lengthy, and we can use the limit_denominator() method to limit the number of digits in the denominator. Let us see this with an example.

As fractions have two parts, namely a numerator and a denominator, there are methods to access both.

from fractions import Fraction
import math
#Fraction(math.pi).limit_denominator(100)
f=Fraction(math.pi).limit_denominator(100)
print("The fraction created is::",f)
print("Numerator::",f.numerator)

Output

The fraction created is:: 311/99
Numerator:: 311

from_float()

We can create fractions from a floating number using the  method.

Fraction.from_float(0.25)

Output

Fraction(1, 4)

ceil() and floor()

We can use the ceil() and floor() methods of the math module to find the nearest integer above or below the fraction value.

import math
math.ceil(Fraction(300, 124))

Output

3

Printing Numbers in different Formats

We can print the numbers in different formats using the format function. We can specify the number of digits we want to print after the decimal point in case of a float number. With the help of the format function and padding operator, we can specify the space after the sign in case of a negative integer.

For e.g, In the following example, the float value is limited to only 6 digits (including the decimal point) in the output with 4 digits after the decimal point. In the case of an integer, the total output is 6 digits including the sign.  

print("Total 6 digits with 4 after the decimal point :::")
print('{:06.4f}'.format(3.141592653589793))
 
print("6 digits including the sign:::")
print('{:=6d}'.format((- 234)))

Output

Total 6 digits with 4 after the decimal point :::
3.1416
6 digits including the sign:::
-  234

As seen in the above output the floating-point number in the output is of total 6 digits and it has 4 digits after the decimal point.
Similarly, the integer output has a total of 6 digits including the negative sign.

Summary of all the Methods

MethodDescription
ceil()To round the number UP to the nearest integer value
floor()To round a number DOWN to the nearest integer value.
degrees()To convert the angle in radians to degrees.
radians()To convert the angle in degrees to radians.
factorial()To find the factorial of any positive integer
fabs() To find a number’s absolute value as a float.
trunc() To truncate a number to its nearest integer
pow() Accepts two arguments, x, and y, and returns the value of x raised to power y
isfinite() and isinf() To find whether a number is finite or not
isclose() To find whether two numbers are close or not using
getcontext() To set the precision of a decimal and set the flags to mention to round the digits up or Down.
limit_denominator() To limit the number of digits in the denominator.
from_float() To create fractions from a floating number
Python Number methods summary

Related Tutorials

  • Python Data Types
  • Python regex find all matches using findall() and finditer()
  • Python random randrange() and randint() to generate random integer number within a range
  • Python range of float numbers
  • Generate Random Float numbers in Python using random() and Uniform()

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python Object-Oriented Programming
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com