Python int() function: Convert Strings, Floats & Booleans to Integers

In real-world programming, you often receive input as text (strings), even when the data represents numbers. To perform mathematical calculations, comparisons, or logical operations, these values must first be converted into integers.

This is where the int() function becomes essential. It allows you to explicitly convert compatible values into whole numbers, ensuring accurate computation and preventing type-related errors.

Before diving deeper into complex examples, explore our complete guide on Explicit Type Casting in Python to understand how type conversion works using different built-in functions.

What is the Python int() Function?

The int() function in Python converts a value into an integer. It transforms numeric strings, boolean values, or other compatible data types into whole numbers for accurate calculations and data processing.

This is especially useful when handling user input, file data, or values received from external sources.

Syntax of Python int() Method

int(x=0, base=10)
Explanation:
Parameter Description
x The value or string to convert into an integer.
base The number base when x is a string (default is 10).

Basic Example of Python int() Method

x = "123"
y = int(x)
print(y)  # Output: 123
print(type(y))  # Output: <class 'int'>
Explanation:

The string “123” is converted into an integer so it can be safely used in arithmetic operations and numeric calculations.

If the value contains a decimal part, int() truncates the fractional portion instead of rounding it, which is an important behavior to remember while working with floating-point numbers.

Example:
print(int(10.9))       
# Output: 10 Floating-point values are truncated, not rounded.

print(int("25"))       
# Output: 25 Numeric strings are converted directly into integers.

print(int(True))       
# Output: 1 Boolean values follow Python’s internal numeric mapping (True → 1, False → 0)

print(int(False))      
# Output: 0

print(int("abc"))  
#ValueError 
Explanation:
  • Here, int() removes any fractional part and converts numeric strings or boolean values into integers.
  • Boolean values follow Python’s internal numeric mapping (True → 1, False → 0).
  • If a non-numeric string such as “abc” is passed, Python raises a ValueError, ensuring type safety at runtime.
  • Passing an invalid string like “abc” raises a ValueError, helping prevent unsafe conversions.

Core Behavior of the int() Function in Python

The int() function in Python follows a small set of strict and predictable rules that apply in every situation. Understanding these core behaviors is essential because they determine how Python interprets numbers, handles invalid input, and treats boolean values during conversion.

(i) Truncation (Not Rounding)

When int() receives a floating-point value, it removes the decimal part entirely instead of rounding the number. This operation is known as truncation toward zero.

Example
print(int(10.9))  # Output: 10
print(int(-4.7))  # Output: -4
Key rule:

int() always truncates toward zero.

Explanation:

The int() function removes everything after the decimal point, even when the fractional value is greater than .5. This truncation behavior works the same for both positive and negative numbers, ensuring consistency.

Although many beginners expect rounding, Python avoids it to keep integer conversions predictable and reliable.

(ii) Error Behavior (ValueError & TypeError)

int() is strict about what it accepts. It raises errors when the input does not conform to its rules.

Example: Invalid string input → ValueError

int("abc") # ValueError
int("12.5") # ValueError
int("123abc") # ValueError
Explanation:

Only valid whole-number strings (with optional + or -) are allowed. Strings containing decimal points, letters, or mixed characters cannot be interpreted as integers and result in a ValueError.

Example: Unsupported types → TypeError

int(None) # TypeError
int([1, 2]) # TypeError
int({"a": 1}) # TypeError
Explanation:

Objects like None, lists, tuples, or dictionaries do not have a direct integer representation. Passing such types to int() violates its conversion rules, so Python raises a TypeError. This strictness helps prevent silent logic errors and forces explicit data validation.

(iii) Boolean Conversion Rules

In Python, boolean values are treated as a special numeric type during integer conversion.

Example:

print(int(True)) # Output: 1
print(int(False)) # Output: 0
Explanation:

The bool type is a subclass of int in Python’s type system, which is why True maps to 1 and False maps to 0. This design allows boolean values to participate naturally in arithmetic operations, counters, and conditional logic.

Python int() Function – Conversion Table

Input TypeBaseInputOutput
Decimal String10“123”123
Binary String2“1010”10
Octal String8“17”15
Hex String16“FF”255
Boolean ValueTrue1

Detailed int() Conversion Scenarios (Explore Further)

While the above examples demonstrate the basic behavior of int(), the function supports many real-world conversion scenarios, especially when working with strings from different numeral systems or dynamic input sources.

To keep this guide clean and easy to navigate, each important scenario is explained in detail on its own dedicated page. You can explore them below:

Topic Description
Converting String to Integer in Python Using int() Learn how Python handles numeric strings, invalid values, and common runtime errors.
Binary String to Integer Conversion in Python Understand how to convert binary numbers (base-2) into integers using int().
Converting Octal String to Integer in Python Covers octal (base-8) conversions, commonly seen in permissions and legacy systems.
Converting Hexadecimal String to Integer in Python Learn how hexadecimal (base-16) values are converted, widely used in memory addresses and color codes.
Examples from User Input – Python int() Function Explore how to safely convert user input into integers, including validation techniques and handling invalid entries.
Examples for Deeper Understanding – Python int() Function Covers advanced usage such as prefixes (0b, 0o, 0x), dynamic base conversion, and safe boolean conversions.
Best Practices and Real-World Example (Base Conversion) Learn recommended practices and real-world scenarios for converting data between different number systems effectively.

Clicking any of the above links will take you to a detailed explanation page with examples, edge cases, and best practices.

Conclusion

Pythons int() function is essential for converting strings and other types into integers.

Key Takeaways:

  • Use int(x) to convert decimal strings to integers.
  • Use int(x, base) to convert binary, octal, or hexadecimal strings.
  • Always validate input before conversion to prevent ValueError.
  • Ideal for user input parsing, file handling, data processing, networking, and low-level programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top