Called on a string, int() parses it as a whole number in the given base (base 10 by default), raising ValueError if the string isn't a valid integer literal. Called on a float, it truncates toward zero rather than rounding, so int(3.9) is 3, not 4. The two-argument form, int(string, base), is handy for parsing hexadecimal, octal, or binary text, e.g. converting the string 'ff' in base 16.
1Understanding int()
Called on a string, int() parses it as a whole number in the given base (base 10 by default), raising ValueError if the string isn't a valid integer literal. Called on a float, it truncates toward zero rather than rounding, so int(3.9) is 3, not 4. The two-argument form, int(string, base), is handy for parsing hexadecimal, octal, or binary text, e.g. converting the string 'ff' in base 16.
int() truncates floats — it does not round them. Use round() first if you want conventional rounding behavior before converting to int.
print(int("42"))
print(int(3.9))
print(int("ff", 16))2Practical Example
Here is a real-world application of int() showing how it is used in production Python code.
user_input = " 128 "
try:
quantity = int(user_input)
print(f"Ordering {quantity} units")
except ValueError:
print("Please enter a whole number")3Best Practices
Follow these guidelines when working with int():
1. Wrap int(user_input) in a try/except ValueError block when parsing untrusted or user-provided text
2. Use int(s, 0) to auto-detect a prefixed base like a hex or binary literal string
3. Prefer int(x) over integer division by 1 for truncating a float to a whole number — it's clearer intent
Tip: int() truncates floats — it does not round them. Use round() first if you want conventional rounding behavior before converting to int.
print(int("42"))
print(int(3.9))
print(int("ff", 16))