TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Numbers & Type Conversion with Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Numbers & Type Conversion with Examples

Last updated: Sep 25, 2023 12:16 am
By Meenakshi Agarwal
Share
11 Min Read
Python Numbers, Type Conversion, and Mathematics
Python Numbers, Type Conversion, and Mathematics
SHARE

Python numbers are a group of four data types: plain integer, long integer, floating-point, and complex numbers. They not only support simple arithmetic calculations but can also be used in quantum computation as complex numbers. In this tutorial, we’ll try to explain each of them with examples.

Contents
The int typeThe long typeThe float typeThe complex typePython numbers – Key pointsType conversion (casting) in PythonExternal classes to handle Python numbersPython mathematics

Let’s see what numbers in Python are. Like other types in Python, numbers are also objects. They can store an integer, a real, or a composite number. Python numbers are immutable objects so any change in the value would lead to the creation of a new object. Usually, assigning a numeric value to a variable will also cause the creation of an object.

>>> num = 10 + 5j # The number object got created.
>>> print(num)
(10+5j)
>>> type(num) # The number is of complex type.
<class 'complex'>
>>> id(num) # The initial address of 'num' in memory.
10171888
>>> num = 11 + 6j # The 'num' gets a new value.
>>> print(num)
(11+6j)
>>> type(num) # The 'num' is still of complex type.
<class 'complex'>
>>> id(num) # Change in value caused 'num' to have a new memory address.
10171952
Python Numbers, Type Conversion, and Mathematics
Python Numbers, Type Conversion, and Mathematics

Python Numbers – Types of Numeric Data

Interestingly, Python 2.x had four built-in data types (int, long, float, and complex) to represent numbers. Later Python 3.x removed the long and extended the int type to have unlimited length.

The int type

The int type represents the fundamental integer data type in Python. The plain integer in Python 2.x had the maximum size up to the value of sys.maxint.

While in 3.x, the int type got promoted to have unlimited length and thus eliminated the long.

>>> x = 9
>>> type(x)
<type 'int'>

Also Read: How to generate random numbers in Python

The long type

An integer number with unlimited length. Until the end of Python 3, the integers were allowed to overflow and turned into a long. This behavior changed since 3.0 when the ints replaced the longs.

>>> x = 9999999999
>>> type(x) # In Python 2.x, the type will be long. While in 3.x, it is int irrespective of the size.
<type 'long'>

The float type

The float represents a binary floating point number. Using a float variable in an expression automatically converts the adjoining longs and ints to floats.

>>> x = 9.999
>>> type(x)
<type 'float'>

The complex type

The number of this type has a real and an imaginary part. For example – The expression (n1 + n2j) represents a complex type where both n1 and n2 are the floating-point numbers denoting the real and imaginary parts respectively.

>>> x = 3 + 4j
>>> type(x)
<class 'complex'>
>>> x.real
3.0
>>> x.imag
4.0

Python numbers – Key points

1. The number types are automatically upcast in the following order: Int → Long → Float → Complex

2. While integers in Python 3.x can be of any length, a float can only take up to fifteen decimal places.

3. Usually, we work with numbers based on the decimal (base 10) number system. But sometimes, we may need to use other number systems such as binary (base 2), hexadecimal (base 16), and octal (base 8).

In Python, we can deal with such numbers using the proper prefixes. See the table below.

Number SystemBasePrefix to Use
BinaryBase-20b or 0B
OctalBase-80o or 0O
HexBase-160x or 0X

Below is a simple illustration of different number systems using Python code.

>>> x = 0b101
>>> print(x)
5
>>> type(x)
<type 'int'>
>>> print(0b101 + 5)
10
>>> print(0o123)
83
>>> type(0x10)
<type 'int'>

4. If you want to test the class type of a number in Python, then you should use the isinstance() function. Here is an example.

>>> isinstance(2.2, float)
True

5. If you use mixed data types in an expression, then all operands will start to behave as the most complex type used.

>>> 2 + 3.8
5.8

6. Be careful while dividing integers in Python. In Python 2, the division (/) will return an integer quotient as the output. Whereas, in Python 3, the division (/) returns a float quotient as the output.

# Python 2.x
>>> 7/2
3
# Python 3.x
>>> 7/2
3.5

7. The floor operator (//) returns the integer quotient, and the mod (%) operator gives the remainder. However, you can get both these by using the divmod() function.

>>> divmod(7, 2)
(3, 1)
>>> 7 % 2
1
>>> 7 / 2
3.5
>>> 7 // 2
3

Type conversion (casting) in Python

In Python, it is pretty easy to convert any numeric data type into another. We call this process coercion in Pythonic terms.

Basic operations such as addition, and subtraction coerce the integer to float implicitly (by default) if one of the operands is a float.

>>> 2 + 4.5
6.5

In the above example, the first integer (2) turned into a float (2.0) for addition, and the output is also a floating point number.

However, Python lays out a number of built-in functions such as int(), float(), and complex() to convert between types explicitly. These functions can even convert strings to numbers.

>>> int(3.7)
3
>>> int(-3.4)
-3
>>> float(3)
3.0
>>> complex(4 + 7j)
(4+7j)

Please note that if you are doing a conversion of a float to an integer, then the number will get truncated (i.e., the integer that is close to zero).

Also Read: XOR Operator in Python

External classes to handle Python numbers

As you’ve read above Python’s built-in float class has a limit to control precision up to the fifteen decimal places. However, there are other limitations as well because it entirely depends on the computer implementation of the floating point numbers. For example, see the below decimal point issue.

>>> 1.1 + 3.2
4.300000000000001

To overcome such type of issues, we can use the decimal module in Python.

Python Decimal

The decimal module provides the fixed and floating point arithmetic implementation which is familiar to most people. Unlike the floating point numbers which have precision up to 15 decimal places, the decimal module accepts a user-defined value. It can even preserve significant digits in a no.

import decimal

print(0.28)

print(decimal.Decimal(0.28))

print(decimal.Decimal('5.30'))

Output-

0.28
0.2800000000000000266453525910037569701671600341796875
5.30

Python Fractions

Python packages a module named ‘fractions,’ to handle fractional numbers.

A fraction combines a numerator and a denominator; both are of integer data type. This module enables rational number arithmetic functionality.

Here is a simple example to create and use Python fraction objects.

import fractions

print(fractions.Fraction(2.5))

print(fractions.Fraction(5.2))

print(fractions.Fraction(3,5))

print(fractions.Fraction(1.3))

print(fractions.Fraction('3.7'))

Output-

5/2
5854679515581645/1125899906842624
3/5
5854679515581645/4503599627370496
37/10

Must Read: Operators In Python

Python mathematics

Python exposes a few built-in functions to carry out simple mathematical calculations.

For example – abs(), cmp(), max(), min(), round().

print(round(55.26,1))

print(round(66.36,-1))

Output – 

55.3
70.0

Apart from the above methods, we can also use the math module in Python. It provides the following common functions to use.

FunctionDescription
abs(x)The absolute value of x: the (positive) distance between x and zero.
ceil(x)The ceiling of x: the smallest integer not less than x.
cmp(a, b)-1 if a < b, 0 if a == b, or 1 if a > b
exp(x)The exponential of x: ex
floor(x)The floor of x: the largest integer not greater than x.
log(x)The natural logarithm of x, for x> 0.
log10(x)The natural logarithm of x, for x> 0.
max(x1, x2,…)The base-10 logarithm of x for x> 0.
min(x1, x2,…)The smallest of its arguments: the value closest to negative infinity
modf(x)The fractional and integer parts of x in a two-item tuple. Both parts share the same sign as x. The integer part coerces into a float.
pow(x, y)The value of x**y
round(x [,n])x rounded to n digits from the decimal point.
sqrt(x)The square root of x for x &gt; 0
piThe mathematical constant pi.
eThe mathematical constant e.

Here are some examples of using the ceil() function.

Example-1

import math

x = math.ceil(3.5)
print(x)
print(math.ceil(2 + 4.2))

Output –

4
7

Example-2

from math import ceil
 
x = 9 / 4
y = ceil(x)
print(y)

Output –

3

Quick Summary – Python Numbers

With the help of Python numbers and the math module, you can do any basic to advanced computations in Python. We hope this tutorial will be able to uplift your learning spirits.

Anyways, if you find something new to learn today, then do share it with others. Also, follow us on our social media accounts to see more in-depth tutorials.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Namespace, Scope, and Scope Resolution Python Namespace Explained
Next Article Python List Concepts Explained with Examples Python Lists

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x