This guide deals with the Python int function and it’s uses, complete with several examples.

The Python int function is used to return an integer from a the object passed into it’s parameters. It can also be used to convert numbers of different bases, (hexadecimal or binary) into integer.

Syntax

The int objects takes two parameters, an object and base.

int(object, base)
  1. object: Insert the value here that of which you want a integer representation. Can be integer, string or float. Can also be things like binary and hexadecimal if base is configured correctly.
  2. base: Specifies the base of the value being inserted. For binary, Base value is 2. For hexadecimal it’s Base 16. And for octal, it’s Base 8. Default is Base 10. Base 10 standard for denary numbers.

Example Set 1:

We’ll be demonstrating the most simple and common use of the int function here. Converting simple strings and float values into integers.

Note that the float value was truncated, not rounded off. It lost any decimal part it had when going through the int() function.

>>> int(5.6)
5

>>> int(5)
5

>>> int('5')
5

>>> int('5332')
5332

Example Set 2:

Here we will discuss handling values belonging to different bases such as Binary and Hexadecimal values.

X = '100'
  
print("Base 2 = ", int(X, 2))  
print("Base 4 = ", int(X, 4))  
print("Base 8 = ", int(X, 8))
print("Base 10 = ", int(X, 10))
print("Base 16 = ", int(X, 16))
Base 2 =  4
Base 4 =  16
Base 8 =  64
Base 10 =  100
Base 16 =  256

This marks the end of the Python int Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments