Python int() Function

Python3 内置函数Python3 Built-in Functions


int()It is one of the most commonly used built-in functions in Python, used to convert data of other types to integer type.

In programming, we often need to convert data of types such as strings, floating-point numbers, or other types into integers for numerical calculations or comparisons.int()This function can help us easily complete this conversion.

Word Definition: intYesintegerAbbreviation of (integer), representing the integer type.


Basic Syntax and Parameters

int()It is a built-in function that can be called directly without importing any module.

Syntax Format

int(x)
int(x, base)

Parameter Description

  • Parameter x:
    • Type: String, number, or other object convertible to an integer
    • Description: The value to convert to an integer. If x is a string, the base can be specified in the base parameter.
  • Parameter base(Optional):
    • Type: Integer (2, 8, 10, 16)
    • Description: The base of x, defaulting to 10 (decimal). Only valid when x is a string.

Function Description

  • Return Value: Returns an integer object.
  • Special Cases:
    • int()Returns 0 when called without arguments
    • Floating-point numbers are rounded down (truncated toward zero)
    • The string must be a valid numeric representation

Examples

Let us, through a series of examples from simple to complex, thoroughly masterint()the usage of int().

Example 1: Basic Usage - Converting Numbers

Examples

# Convert from floating-point number
print(int(3.7))      # Output: 3
print(int(-3.7))     # Output: -3

# Convert from boolean value
print(int(True))     # Output: 1
print(int(False))    # Output: 0

# Convert from string
print(int("42"))     # Output: 42
print(int("  10  ")) # Output: 10 (whitespace automatically removed)

Expected output:

3
-3
1
0
42
10

Code analysis:

  1. When a floating-point number is converted to an integer, the decimal part is truncated directly (rounded toward zero), rather than rounded to the nearest integer.
  2. Boolean valuesTrueTrue converts to 1, andFalseFalse converts to 0.
  3. When converting a string, leading and trailing whitespace characters are automatically removed.

Example 2: Base Conversion

int()It supports converting strings in different bases to decimal integers.

Examples

# Binary string (starting with 0b)
print(int("1010", 2))   # Output: 10

# Octal string (starting with 0o)
print(int("12", 8))     # Output: 10

# Hexadecimal string (starting with 0x)
print(int("a", 16))     # Output: 10
print(int("FF", 16))    # Output: 255

# String with prefix
print(int("0b1010", 2)) # Output: 10
print(int("0o12", 8))   # Output: 10
print(int("0xff", 16))  # Output: 255

Expected output:

10
10
10
255
10
10
255

Code analysis:

  • The second parameter specifies the numeric base of the string: 2 means binary, 8 means octal, and 16 means hexadecimal.
  • The string can have a prefix (such as0b, 0o, 0x), or it can be without one.
  • In hexadecimal, a-f can be uppercase or lowercase.

Example 3: Common Application Scenarios

int()It has many application scenarios in actual programming, such as user input processing, data cleaning, and so on.

Examples

# Handle user input (input returns a string)
# Assume the user entered "100"
user_input = "100"
price = int(user_input)
print(f"Product price: {price} yuan")  # Output: Product price: 100 yuan

# Numeric strings read from a file
numbers_str = ["10", "20", "30"]
numbers = [int(n) for n in numbers_str]
print(numbers)  # Output: [10, 20, 30]

# Calculate the total
total = sum(numbers)
print(f"Total: {total}")  # Output: Total: 60

# Handle a string with decimals (convert to float first, then to int)
price_str = "19.99"
price = int(float(price_str))
print(f"Price (rounded): {price} yuan")  # Output: Price (rounded): 19 yuan

Expected output:

商品价格: 100 元
[10, 20, 30]
总和: 60
价格(取整): 19 元

This example demonstratesint()the common usage of int() in practical applications, including handling user input, batch data conversion, and so on.


Python3 内置函数Python3 Built-in Functions


Other Extensions