int()
Python · Variables & Data Types
Theory
int() builds a whole-number int from another value. Given a float it truncates toward zero, simply chopping off the decimal part, so int(4.9) is 4 and int(-4.9) is -4; it never rounds (use round() for that). Given a string, the text must look like a whole number: surrounding spaces are allowed, so int(' 42 ') is 42, but int('4.5') and int('abc') raise ValueError. Booleans convert too: int(True) is 1.
An optional second argument sets the base of the text: int('ff', 16) is 255 and int('101', 2) is 5. The result is always a brand-new int object; the original value is unchanged. A very common use is converting user input or CSV fields, which always arrive as strings, into numbers you can calculate with.
Why we use it
Data from files, forms, APIs and input() arrives as text. You cannot add or compare '25' as a number until you convert it, and int() is the standard, strict way to do that conversion.
When to use it
Use int() for counts, IDs and quantities read as text. For a string like '4.5', convert with float() first and then int() if you really want to truncate. Wrap int() in try/except ValueError when the input might be dirty.
How it works
- int(value) is called
- Is value a float? Yes: Drop the decimal part (truncate toward zero). No: Go on to the next check.
- Is value a string? Yes: Strip spaces and parse the digits in the given base. No: Use its integer meaning (True -> 1).
- Was the text a valid whole number? Yes: Return the new int. No: Raise ValueError.
- e.g. int('25') returns 25 of type int
Syntax
int(value)Example
age = int("25")
print(age, type(age))Key points
- Truncates any decimal portion rather than rounding: int(4.9) is 4
- Truncation is toward zero: int(-4.9) is -4
- Raises a ValueError on non-numeric text like int("abc") and on '4.5'
- Leading and trailing spaces are allowed: int(' 42 ') is 42
- int('ff', 16) converts from another base