Python int() Function



The Python int() function is used to convert a given value into an integer. It can convert various types of data, such as numeric strings or floating-point numbers, into integers.

If the given value is a floating-point number, the int() function truncates the decimal part, returning the whole number. Additionally, it can be used with a second argument to specify the base for converting numbers from binary, octal, or hexadecimal representations to decimal integers.

Syntax

Following is the syntax of Python int() function −

int(x [,base])

Parameters

This function takes two parameters as shown below −

  • x − It represents the value that you want to convert to an integer.

  • base (optional) − It specifies the base of the given number; default is 10, and it takes "x" as a string in that base for conversion.

Return Value

This function returns an integer object.

Example 1

Following is an example of the Python int() function. Here, we are converting the string "123" to an integer −

string_num = "123"
integer_num = int(string_num)
print('The integer value obtained is:',integer_num)

Output

Following is the output of the above code −

The integer value obtained is: 123

Example 2

Here, we are converting the floating-point number "7.8" to an integer using the int() function −

float_num = 7.8
int_num = int(float_num)
print('The corresponding integer value obtained is:',int_num)

Output

We can see in the output below that the decimal part is truncated −

The corresponding integer value obtained is: 7

Example 3

If you pass a string containing non-numeric characters to the int() function, it will raise a ValueError.

Here, we are converting the string "42 apples" into an integer −

# Example with Error
mixed_string = "42 apples"
number_part = int(mixed_string)
print(number_part)

Output

We can see in the output below that an issue arises because the string contains non-numeric characters (' apples'), causing a ValueError during the conversion −

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    number_part = int(mixed_string)
ValueError: invalid literal for int() with base 10: '42 apples'

Example 4

Now, we handle a string containing both numeric and non-numeric characters.

First, we extract only the numeric characters from the "mixed_string." We create the "numeric_part" variable using a list comprehension that filters out non-numeric characters, resulting in a string with only digits "42". Finally, we use the int() function to convert this string into an integer −

# Example without Error
mixed_string = "42 apples"
numeric_part = ''.join(char for char in mixed_string if char.isdigit())
number_part = int(numeric_part)
print('The integer value obtained is:',number_part)

Output

The result produced is as follows −

The integer value obtained is: 42
python_type_casting.htm
Advertisements