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
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
Converting a floating-point number to an integer: The fractional part is truncated when converting a float to an integer.
Converting a string to an integer: The string must represent a valid number, and it can also be in a specific base.
Using
int()
without arguments: When called without arguments,int()
returns0
.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.
Converting with different number bases: You can pass strings representing numbers in different bases and specify the base.
Using
int()
with objects: Any object that defines the__int__()
method can be passed toint()
.
Handling Errors
- If the input is a string and is not a valid number or if the base is not appropriate,
int()
raises aValueError
. - If you pass a non-numeric string, Python will throw an error:
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
.