CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Numeric Types – int Class

Numeric Types in Python are used to deal with numeric values. Python provides different classes to deal with numeric data; int, float, complex fractions and decimal are those classes.

In this Article,  I will explain int class which is used to deal with integers.

Let’s look at this class and usage of it in Python.

int Class – Deal with Integers

In Python everything represents in objects. For example, the number “2” is a value of the int object. Below code clarifies this:

>>> type(2)
<class 'int'>

Integer variables can be created by directly assigning the integer values or using the class constructor int(). If no argument is passed to the int() constructor, it creates a “0” value integer. That means argument to the constructor is optional:

>>> int()
0

To create an integer with the value 90, we pass the value 90 to the int() constructor. Here is the example:

>>> a = int(90)
>>> a
90

And notice it’s type.

>>> type(a)
<class 'int'>

Another interesting variation of int() constructor is used to represent the integer value and it’s base system.

The Syntax of it is:

int(numerical_string, base_system = 10)

The first argument is the numerical string. The second argument base_system is optional and it represents in which base system the numerical string is defined. By default it is base 10.

The meaningful values are 2 (for binary), 8 (for Octal) and 16 ( for Hexadecimal). That means, if you specify 16 in the second argument as the base system; you must pass the hexadecimal string value in the first argument. Otherwise, Python throws ValueError. Below examples explains the usage of this constructor.

>>> int("90", 10)
90
>>> int("1011010", 2)
90
>>> int("132", 8)
90
>>> int("5A", 16)
90

Let’s see what will happen if we pass wrong value.

>>> int("90", 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '90'

From above example, we passed the value “90” which is in base 10. But we mentioned that it is in base 2; which is wrong. Hence the Error.

We will discuss more topics in my upcoming Articles.

/Shijit/

Python – Numeric Types – int Class

One thought on “Python – Numeric Types – int Class

Leave a Reply

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

Scroll to top