The Python int function serves the purpose of obtaining the integer representation of a value. It returns the result of an expression that has been transformed into an integer. In cases where the input is a floating-point number, the conversion process discards the decimal portion. Furthermore, if the provided argument exceeds the range of standard integers, it will be converted into a long type instead.
In cases where the value is not a numerical type or when a specific base is provided, the number should be represented as a string.
Python int Function Syntax
It has the following syntax:
int(x, base=10)
Parameters
- x : A number which is to be converted into integer type.
- base : It is an Optional argument if used number must be a string.
Return
It returns an integer value.
Different Examples for Python int Function
Let us examine a few instances of the int function to gain a better understanding of its capabilities.
Python int Function Example 1
This is a straightforward Python example that transforms both float and string representations of numeric values into an integer type. The function truncates the float value and subsequently returns it as an integer.
# Python int() function example
# Calling function
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)
Output:
integer values : 10 10 10
Python int Function Example 2
To confirm the type of a value that has been returned, one can utilize the type function. This function provides the specific type of the value in question. Refer to the example provided below.
# Python int() function example
# Declaring variables
val1 = 10 # integer
val2 = 10.52 # float
val3 = '10' # string
# Checking values's type
print(type(val1), type(val2), type(val3))
# Calling int() function
val4 = int(val1)
val5 = int(val2)
val6 = int(val3)
# Displaying result
print("values after conversion ",val4, val5, val6)
print("and types are: \n ", type(val4), type(val5), type(val6))
Output:
<class 'int'> <class 'float'> <class 'str'>
values after conversion 10 10 10
and types are:
<class 'int'> <class 'int'> <class 'int'>
Python int Function Example 3
Let's explore an additional example to illustrate the functionality of the Python int function.
# Python int() function example
# Declaring variables
val1 = 0b010 # binary
val2 = 0xAF # hexadecimal
val3 = 0o10 # octal
# Calling int() function
val4 = int(val1)
val5 = int(val2)
val6 = int(val3)
# Displaying result
print("Values after conversion:",val4, val5, val6)
print("and types are: \n ", type(val4), type(val5), type(val6))
Output:
Values after conversion: 2 175 8
and types are:
<class 'int'> <class 'int'> <class 'int'>