Python int() function


The int() function in Python is used to convert a given value into an integer. If no arguments are provided, it returns 0. It can handle different types of inputs, such as strings, floating-point numbers, and even numbers in different bases (like binary or hexadecimal).

Syntax

int([x], [base=10])
  • x (optional): The value to be converted to an integer. It can be a string, float, or any object that implements the __int__() method.
  • base (optional): The base of the number in string form. It defaults to 10 but can be set to other bases like 2, 8, or 16.

Return Value

  • Returns an integer representation of the input.
  • Raises a ValueError if the input cannot be converted to an integer.

Examples

  1. Converting a floating-point number to an integer: The fractional part is truncated when converting a float to an integer.

    print(int(5.7)) # Output: 5
  2. Converting a string to an integer: The string must represent a valid number, and it can also be in a specific base.

    print(int("42")) # Output: 42 print(int("1010", 2)) # Output: 10 (binary to decimal) print(int("1F", 16)) # Output: 31 (hexadecimal to decimal)
  3. Using int() without arguments: When called without arguments, int() returns 0.

    print(int()) # Output: 0
  4. Converting a float string to an integer: You cannot directly convert a float string to an integer. You would first convert the string to a float and then to an integer.

    print(int(float("5.9"))) # Output: 5
  5. Converting with different number bases: You can pass strings representing numbers in different bases and specify the base.

    print(int("110", 2)) # Output: 6 (binary to decimal) print(int("77", 8)) # Output: 63 (octal to decimal)
  6. Using int() with objects: Any object that defines the __int__() method can be passed to int().

    class MyNumber: def __int__(self): return 100 num = MyNumber() print(int(num)) # Output: 100

Handling Errors

  • If the input is a string and is not a valid number or if the base is not appropriate, int() raises a ValueError.
  • If you pass a non-numeric string, Python will throw an error:
    print(int("hello")) # Raises ValueError: invalid literal for int()

Summary

  • The int() function converts a value into an integer.
  • It can take optional arguments: a value and a base for string conversions.
  • It supports conversions from strings, floats, and objects that define the __int__() method.
  • If no argument is provided, it returns 0.