Python int()
Function
The int() function in Python converts a number or a string into an integer. It's one of the most commonly used functions in Python programming.
Syntax
int(x=0, base=10)
Parameters:
x
– A number (like float or string) to convert to an integer. Default is0
.base
– (Optional) The base of the number (used only ifx
is a string). Default is 10.
Returns:
- An integer representation of the input.
Example 1: Convert Float to Integer
print(int(5.9))
5
Note: It truncates the decimal part (does not round).
Example 2: Convert String to Integer
print(int("42"))
42
Example 3: Convert Binary String to Integer
print(int("101", 2))
5
Example 4: Convert Hexadecimal String to Integer
print(int("1A", 16))
26
Use Cases
- Converting user input (strings) into usable numeric values
- Truncating float values into whole numbers
- Converting from binary, octal, or hexadecimal to decimal
Common Mistakes
- Passing a string with letters in base 10:
int("abc")
→ValueError
- Using invalid bases (must be between 2 and 36)
- Passing
None
or an empty string: causesTypeError
orValueError
Interview Tip
The int()
function is frequently used in string parsing, input handling, and base conversions — all common in coding interviews.
Summary
int()
converts numbers and strings to integers.- If a float is passed, it truncates the decimal part.
- If a string is passed with a base, it converts from that base.
Practice Problem
Write a program that asks the user to enter a number and prints the number as an integer.
user_input = input("Enter a number: ")
try:
print("As integer:", int(user_input))
except ValueError:
print("That's not a valid number!")