Python’s int()
function is a built-in method that converts a given value to an integer. This versatile function plays a crucial role in type conversion and mathematical operations in Python. In this detailed guide, we’ll explore the functionalities of int()
with comprehensive examples to help you understand its usage thoroughly.
Basic Usage:
# Example 1: Converting a string to an integer
str_num = "42"
int_num = int(str_num)
print(int_num)
Output:
42
In this example, the string "42"
is converted to an integer using the int()
function.
Converting Floats to Integers:
# Example 2: Converting a floating-point number to an integer
float_num = 3.14
int_from_float = int(float_num)
print(int_from_float)
Output:
3
When converting a floating-point number to an integer, int()
truncates the decimal part.
Handling Binary and Hexadecimal Strings:
# Example 3: Converting binary and hexadecimal strings to integers
binary_str = "1010"
hex_str = "1A"
int_from_binary = int(binary_str, 2)
int_from_hex = int(hex_str, 16)
print(int_from_binary)
print(int_from_hex)
Output:
10
26
Using int()
with an optional base parameter, you can convert binary or hexadecimal strings to integers.
Error Handling:
# Example 4: Handling ValueError for invalid inputs
invalid_str = "abc"
try:
int_num = int(invalid_str)
except ValueError as e:
print("Error:", e)
Output:
Error: invalid literal for int() with base 10: 'abc'
If the string passed to int()
cannot be converted to an integer, a ValueError
is raised.
Using int() with Custom Objects:
# Example 5: Converting custom objects to integers
class MyClass:
def __int__(self):
return 42
my_obj = MyClass()
int_from_obj = int(my_obj)
print(int_from_obj)
Output:
42
Custom objects can define a __int__()
method to specify how they should be converted to integers using int()
.