Python3 Func Int
## Python int() Function
The `int()` function is one of Python's most frequently used built-in functions. It is primarily used to convert other data typesβsuch as floats, booleans, and stringsβinto integers.
In programming, converting data types is a common necessity. For instance, when reading user input or parsing files, numbers are often represented as strings. The `int()` function allows you to easily convert these representations into actual integer types for numerical calculations, comparisons, and logic.
---
## Syntax and Parameters
Since `int()` is a built-in function, it is globally available and does not require importing any external modules.
### Syntax
```python
int(x=0)
int(x, base=10)
```
### Parameters
* **`x`** (Optional):
* **Type**: String, bytes, bytearray, number, or any object that implements the `__int__()` or `__index__()` magic methods.
* **Description**: The value you want to convert to an integer. If `x` is a string, you can specify its base using the `base` parameter. If no arguments are passed, it defaults to `0`.
* **`base`** (Optional):
* **Type**: Integer (ranging from `2` to `36`, or `0`).
* **Description**: The mathematical base (radix) of the number represented by the string `x`. It defaults to `10` (decimal). **Note:** This parameter can only be used when `x` is a string, bytes, or bytearray.
### Return Value
* Returns an integer object representing the converted value.
---
## Key Behaviors and Rules
* **No Arguments**: Calling `int()` without any arguments returns `0`.
* **Floating-Point Truncation**: When converting a float to an integer, Python truncates the decimal part (rounds toward zero) rather than rounding to the nearest whole number.
* **String Constraints**: When converting a string, the string must represent a valid integer. Passing a string with a decimal point (e.g., `"19.99"`) directly to `int()` will raise a `ValueError`.
* **Whitespace Handling**: Leading and trailing whitespaces in strings are automatically stripped.
---
## Code Examples
### Example 1: Basic Conversions (Numbers, Booleans, and Strings)
This example demonstrates how `int()` handles basic data types.
```python
# Converting from floats (truncates toward zero)
print(int(3.7)) # Output: 3
print(int(-3.7)) # Output: -3
# Converting from booleans
print(int(True)) # Output: 1
print(int(False)) # Output: 0
# Converting from standard decimal strings
print(int("42")) # Output: 42
print(int(" 10 ")) # Output: 10 (automatically strips leading/trailing whitespace)
```
**Expected Output:**
```text
3
-3
1
0
42
10
```
---
### Example 2: Base Conversions (Binary, Octal, Hexadecimal)
By using the `base` parameter, you can parse non-decimal string representations into decimal integers.
```python
# Binary strings (Base 2)
print(int("1010", 2)) # Output: 10
# Octal strings (Base 8)
print(int("12", 8)) # Output: 10
# Hexadecimal strings (Base 16)
print(int("a", 16)) # Output: 10
print(int("FF", 16)) # Output: 255
# Parsing strings with explicit prefixes
print(int("0b1010", 2)) # Output: 10 (Binary prefix '0b')
print(int("0o12", 8)) # Output: 10 (Octal prefix '0o')
print(int("0xff", 16)) # Output: 255 (Hexadecimal prefix '0x')
```
**Expected Output:**
```text
10
10
10
255
10
10
255
```
**Key Takeaways:**
* The `base` parameter specifies the radix of the input string.
* The input string can optionally include standard Python prefixes like `0b` (binary), `0o` (octal), or `0x` (hexadecimal).
* For hexadecimal conversions, letters `a-f` (or `A-F`) are case-insensitive.
---
### Example 3: Practical Application Scenarios
Here is how `int()` is typically used in real-world development, such as handling user inputs, processing collections, and cleaning data.
```python
# Scenario 1: Processing user input (input() always returns a string)
# Simulating user input of "100"
user_input = "100"
price = int(user_input)
print(f"Item Price: {price} USD") # Output: Item Price: 100 USD
# Scenario 2: Converting a list of numeric strings from a file or API
numbers_str = ["10", "20", "30"]
numbers = [int(n) for n in numbers_str]
print(numbers) # Output: [10, 20, 30]
# Performing mathematical operations on the converted list
total = sum(numbers)
print(f"Total Sum: {total}") # Output: Total Sum: 60
# Scenario 3: Handling decimal strings
# Direct conversion of "19.99" to int raises ValueError.
# Instead, parse to float first, then convert to int.
price_str = "19.99"
truncated_price = int(float(price_str))
print(f"Truncated Price: {truncated_price} USD") # Output: Truncated Price: 19 USD
```
**Expected Output:**
```text
Item Price: 100 USD
[10, 20, 30]
Total Sum: 60
Truncated Price: 19 USD
```
---
## Important Considerations & Error Handling
When working with `int()`, you should be aware of potential runtime errors:
1. **ValueError on Invalid Strings**:
If you pass a string that does not represent a valid integer, Python will raise a `ValueError`.
```python
int("12.34") # ValueError: invalid literal for int() with base 10: '12.34'
int("abc") # ValueError: invalid literal for int() with base 10: 'abc'
```
*Solution*: For decimal strings, convert to a float first using `float()`, or wrap your conversion in a `try-except` block to handle unexpected inputs gracefully.
2. **TypeError on Unsupported Types**:
Passing an incompatible object type (like a `list` or `dict`) will raise a `TypeError`.
```python
int([1, 2]) # TypeError: int() argument must be a string, a bytes-like object or a real number
```
YouTip