Python / int() / Convert Values to Integers
Python’s int() converts an integer-form string or a supported number into an integer object. Floating-point values are truncated toward zero, so int(-2.7) is -2, rather than a rounded or floored result. A string containing a decimal point, such as "12.0", cannot be converted directly.
Basic conversion and return values
int(value) returns an int; omitting the argument returns zero. Strings use base ten by default and accept surrounding whitespace, a sign, and correctly placed underscores between digits. Booleans True and False become 1 and 0. See the official int() reference for supported forms.
These examples need Python 3. Save each complete example in UTF-8 as int_example.py and run python int_example.py, or python3 where appropriate. Replace the file contents to run each example independently.
print(int())
print(int(" +123 "))
print(int("1_024"))
print(int(True), int(False))
text = "12"
number = int(text)
print(number + 3, type(number).__name__)
print(text, type(text).__name__)
Expected output:
0
123
1024
1 0
15 int
12 str
Assigning the converted value to another variable leaves the original string unchanged. Converting "12" lets you add the number 3 to obtain 15. If a count must not accept Boolean values, reject them separately rather than relying on successful conversion.
Truncation is different from rounding and flooring
Truncation toward zero removes the fractional part for either sign. In contrast, math.floor() chooses the greatest integer no larger than the value, which differs for negative numbers. The columns below show the original value, int(), math.floor(), and round().
import math
for value in (2.7, -2.7):
print(value, int(value), math.floor(value), round(value))
2.7 2 2 3
-2.7 -2 -3 -3
For -2.7, int() gives -2 and floor() gives -3. Choose a rounding function when your calculation requires rounding. An existing float may already contain representation error; integer conversion cannot recover an intended decimal value that was lost earlier.
Parsing binary and hexadecimal strings with base
int(text, base) specifies the numeral system used by the input. Bases are 2–36 or 0; zero detects prefixes such as 0b, 0o, and 0x. When supplying a base, the first argument must be a string or a supported bytes-like form, rather than a numeric object.
print(int("1010", 2))
print(int("ff", 16))
print(int("0xff", 0))
print(int("0b1010", 0))
print(int("010"))
print(int("010", 8))
try:
print(int("010", 0))
except ValueError:
print("ValueError")
10
255
255
10
10
8
ValueError
"010" is ten with the default base and eight with base eight. With base zero, this leading-zero form without a prefix is rejected. The returned integer does not retain a hexadecimal display format; use hex() or format() separately to control its presentation.
Conversion errors and large integer precision
An invalid representation can raise ValueError; an unsupported type can raise TypeError. Infinity raises OverflowError, while NaN, meaning “not a number,” raises ValueError. This example catches only the expected exceptions so it can inspect subsequent inputs.
for value in ("12.0", "1e3", "1,000", "", None, float("nan"), float("inf")):
try:
print(repr(value), int(value))
except (ValueError, TypeError, OverflowError) as error:
print(repr(value), type(error).__name__)
'12.0' ValueError
'1e3' ValueError
'1,000' ValueError
'' ValueError
None TypeError
nan ValueError
inf OverflowError
Using int(float(text)) changes the policy: it parses decimal or exponent notation and then truncates. Large integer strings may lose information during the float step because of floating-point representation limits.
text = "9007199254740993"
print(int(text))
print(int(float(text)))
9007199254740993
9007199254740992
Parse integer strings directly with int(text) when accuracy matters. Python integers are not restricted to a fixed 32-bit or 64-bit range, although memory and other resources remain finite. Since Python 3.11, integer string conversion limits may also restrict very long conversions in some bases. Bound external input to useful lengths and value ranges instead of simply disabling these limits.
Validating a string as a non-negative count
Successful conversion does not establish that a value is valid for your application. This function accepts strings, converts them, and rejects negative results. Its count includes zero and deliberately retains int()’s accepted signs, whitespace, and underscores.
def parse_count(text):
if not isinstance(text, str):
raise TypeError("text must be a string")
value = int(text)
if value < 0:
raise ValueError("count must be non-negative")
return value
for text in (" 3 ", "-1", "2.5", ""):
try:
print(repr(text), parse_count(text))
except ValueError:
print(repr(text), "invalid count")
' 3 ' 3
'-1' invalid count
'2.5' invalid count
'' invalid count
Invalid counts raise ValueError. An input interface can use exception handling to request another value. Add an upper bound for quantities or a separate character check if only ASCII digits are allowed. Turning every invalid value into zero would make an error indistinguishable from a genuine zero.




