What Does the int Function Do in Python?

Python programming is one of the easiest programming languages of the present time. Handling data types on its own is one of the significant aspects of that. However, if we accept data input from the user, it stores it as a string. Have you ever thought about how we can use it to do some essential operations on them? Yes, we need to typecast (converting the data type of an object) into the desired data type. Now, the question arises of how we can typecast it. So, today in this article, we will see how we can typecast a string into an integer datatype using the int() function. Besides that, it is also used for other different purposes we will discuss them all.

What is Int() Function in Python?

So, the int() function is an inbuilt python function used to convert any supported data type to an integer. The supported data type can be a string, a bytes-like object, or a floating-point number. Besides that, it is also used to convert a byte string to its decimal form provided its base. In simple words, if you choose the base 2, it means it is a binary number, and you want to convert it into an integer. Similarly, if the base is 3, you must convert a ternary number to an integer. Now, if you understood the concept of int() function, let’s see its syntax and usage.

Syntax :

int(<supported-datatype>[,base])

[ Note: The point to keep in mind is that if you pass any invalid literal with the base, it throws a value error. It means that if you want to convert a binary number to an integer, then the first argument should be a binary number. Else system raises the error.]

Examples on Int() Function

Now, it’s time to see some of the examples.

Example 1: Converting Datatypes as Integer

# Converting string into integer
string1 = '143'
print(type(string1))
num1 = int(string1)
print(num1)
print(type(num1))

# Converting floating point number into integer
flt = 2.24
print(flt)
print(type(flt))
num2 = int(flt)
print(num2)
print(type(num2))

Output:

<class 'str'>
143
<class 'int'>
2.24
<class 'float'>
2
<class 'int'>

Example 2: Converting into integers using Base Value

# Converting binary into decimal
# We choose base value = 2
binary = '1000'
decimal = int(binary,2)
print(decimal)
print(type(decimal))

# Converting ternary into decimal
# We choose base value = 3
ternary = '2000'
decimal = int(ternary,3)
print(decimal)
print(type(decimal))

Output:

8
<class 'int'>
54
<class 'int'>

Example 3: Type Error while using unsupported datatype

lst = ['a','b']
# trying to convert an unsupported datatype
print(int(lst))

Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-41351cb964d2> in <module>()
      1 lst = ['a','b']
----> 2 print(int(lst))

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

In the above example, We tried to convert a list into an integer data type, which is impossible. Hence the system raises Type Error.

Example 4: Invalid values while converting Binary numbers

num = int('143',2)
print(num)

Output:

ValueError                                Traceback (most recent call last)
<ipython-input-5-54d0607b9c72> in <module>()
----> 1 num = int('143',2)
      2 print(num)

ValueError: invalid literal for int() with base 2: '143'

We tried to convert a decimal number into integers by specifying it as a binary number. This raises the value error. So we have to pass a binary number with the base 2.

Other way of converting String to Int

Besides the int() function, we have another method used to convert a string into an integer. We can use ast.literal_eval() method to do so. We will pass the string as the function’s argument and return it as the integer. Let’s see the example.

import ast

x = '124'
print(ast.literal_eval(x))
print(type(ast.literal_eval(x)))

Output:

124
<class 'int'>

Difference between round() and int()

Using the int () method, we can convert a floating-point number into an integer using the int() method. We can also do the same using the round() function. However, its scope is far more than that. The round() function is also used to set the precision of a floating-point number. We have to pass the precision point as the second argument for the number to do that. However, if we don’t pass any second argument, it will return an integer to the nearest round of the number. It means if the decimal of the number is greater than “.5,” it will return the next integer, and if it is less than “0.5”, it will return the number itself without decimal. Let’s see the example.

x = 12.7899
print("int() function returns x as",int(x))
print("round() function returns x as",round(x))

y = 12.345
print("int() function returns y as",int(y))
print("round() function returns y as",round(y))

Output:

int() function returns x as 12
round() function returns x as 13
int() function returns y as 12
round() function returns y as 12

Difference between int() and math.floor()

The floor() function returns the floor value of x but not the largest number greater than x. On the other hand, int() returns the integer value of any floating-point number or converts the one number representation into other. Let’s see the example.

import math
x = 12.7899
print("int() function returns x as",int(x))
print("math.floor() function returns x as",math.floor(x))

x = -12.3
print("int() function returns x as",int(x))
print("math.floor() function returns x as",math.floor(x))

Output:

int() function returns x as 12
math.floor() function returns x as 12
int() function returns x as -12
math.floor() function returns x as -13

FAQs on Python int Function

Q1) What is the default base value in int()?

10 is the default base value of the int() function.

Q2) Does int() work on strings?

No, the int() function does not work on the string. However, if the string contains the integer value, it converts it into an integer. Still, if the string has a group of characters, it raises an invalid string literal error.

Q3) Does int() work on lists?

We can’t directly apply the int() function on the list. However, we can use list comprehension to convert elements of a list into integers. Let’s see the example.

lst = ['1','2','3','4']
print('List comprised of string',lst)
x = [int(m) for m in lst]
print('List comprised of integer',x)


Output:

List comprised of string ['1', '2', '3', '4'] List comprised of integer [1, 2, 3, 4]

Conclusion

So, today in this article, we will learn about the python int() function. We have seen the purpose of its use. Then we have seen examples to understand it. Then we have seen possible errors while handling the int() function. I hope this article has helped you. Thank You.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments