The int()
function converts a number or string into an integer. It’s useful for math operations, handling user input, and working with numerical data.
Example
num = int("10")
print(num)
# Output: 10
This converts a string into an integer.
Syntax
int(value, base=10)
- value → The number or string to convert.
- base (optional) → The base for conversion (default is
10
). - Returns → An integer.
1. Converting Floats to Integers
The decimal part is removed (not rounded).
print(int(5.9))
# Output: 5
Useful when you need whole numbers only.
2. Converting Strings to Integers
num = int("123")
print(num)
# Output: 123
Works if the string contains only digits.
3. Converting Binary, Octal, and Hexadecimal
Use base
to convert numbers from different bases.
print(int("101", 2)) # Binary to decimal → Output: 5
print(int("77", 8)) # Octal to decimal → Output: 63
print(int("1F", 16)) # Hex to decimal → Output: 31
Great for working with different numbering systems.
4. Handling User Input Safely
try:
age = int(input("Enter your age: "))
print("Your age:", age)
except ValueError:
print("Invalid input! Please enter a number.")
Prevents crashes when users enter non-numeric values.
Key Notes
- ✔ Converts numbers and strings to integers.
- ✔ Ignores decimal parts (does not round).
- ✔ Supports different bases (binary, octal, hex).
- ✔ Handle user input safely with
try-except
.
By using int()
, you can work with numerical data easily, making your code efficient and error-free. 🚀