Python int() Function

Python int() function is “used to convert a number or a string to its equivalent integer.” 

Syntax

int(value, base)

Parameters

  1. value: It is a parameter is a number or a string that can be converted into an integer number.
  2. base: It is a parameter is a number representing the number format. The default value is 10.

Return value

The int() method returns:

  1. integer portion: For a single argument value (any number).
  2. 0: For no arguments.
  3. integer representation of a number with a given base (0, 2, 8, 10, 16).

Example 1: How does the int() function work?

data = "1921"

print(int(data))

Output

Python Int Function Tutorial

The int() function returns,

  1. The integer object from a given number or string treats the default base as 10.
  2. If there are no parameters, then it returns a 0.
  3. If the base has been given, it treats the string in the given base (0, 2, 8, 10, 16).

Example 2: int() function with two arguments

# converting a string (that is in binary format) to integer
print("For 0b1101, int is:", int("0b1101", 2))

# converting a string (that is in octal format) to integer
print("For 0o23, int is:", int("0o23", 8))

# converting a string (that is in hexadecimal format) to integer
print("For 0xB, int is:", int("0xB", 16))

Output

For 0b1101, int is: 13
For 0o23, int is: 19
For 0xB, int is: 11

Example 3: int() for custom objects

class Student:
  rollno = 21

  def __index__(self):
    return self.rollno


student = Student()

print("int(Student) is:", int(student))

Output

int(Student) is: 21

Example 4: TypeError: int() can’t convert non-string with explicit base

print(int(0b101, 2))

Output

TypeError: int() can't convert non-string with explicit base

Example 5: ValueError: invalid literal for int() with base 10: ”

print(int("database"))

Output

ValueError: invalid literal for int() with base 10: 'database'

Example 6: int() with __index__() function

class Data:
  num = 21

  def __index__(self):
    return self.num

data = Data()
print("Data =", int(data))

Output

Data = 21

Recommended Readings:

  1. Python bin()
  2. Python hex()

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.