How to use the int() function in Python
Learn to use integers in Python with our guide. We cover different methods, tips, real-world applications, and how to debug common errors.
%2520function%2520in%2520Python.png)
In Python, the int data type is a fundamental tool to handle whole numbers. It supports many operations, from simple arithmetic to complex data analysis and control flow decisions.
In this article, you'll explore techniques to manipulate integers and find practical tips. You'll also see real-world applications and get advice to debug common int-related errors in your code.
Basic creation and usage of int values
# Creating integers
x = 10
y = -25
z = x + y
print(f"x: {x}, y: {y}, sum: {z}")--OUTPUT--x: 10, y: -25, sum: -15
The code snippet highlights Python's flexibility with integers. You can assign whole numbers like 10 and -25 directly to variables. Because of Python's dynamic typing, you don't need to explicitly declare the int type; it's inferred automatically, which helps keep your code clean and readable.
Arithmetic operations are also intuitive. The + operator works directly on these int variables, as seen with z = x + y, to produce the sum. This seamless integration allows you to focus on your program's logic rather than on type management.
Common integer operations
Beyond basic assignment and arithmetic, you'll often need to convert other data types to integers or use Python's built-in functions to handle more complex operations.
Converting other types to int
string_num = "42"
float_num = 3.14
binary_string = "1010"
print(int(string_num))
print(int(float_num))
print(int(binary_string, 2))--OUTPUT--42
3
10
The built-in int() function is your go-to for converting other data types into integers. It’s a versatile tool that handles various conversion scenarios cleanly.
- When you pass a string like
"42", it’s parsed into its integer equivalent. - For floating-point numbers such as
3.14,int()truncates the decimal part, resulting in3. It doesn't round. - You can also convert numbers from other bases. For example,
int("1010", 2)interprets the string as a binary number and converts it to the decimal integer10.
Performing arithmetic with int
a = 10
b = 3
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Integer division: {a // b}")
print(f"Modulus: {a % b}")--OUTPUT--Addition: 13
Subtraction: 7
Multiplication: 30
Integer division: 3
Modulus: 1
Python handles standard arithmetic with familiar operators like +, -, and *. The snippet also highlights two operators that are especially useful for integer-specific tasks.
- Integer division (
//) performs division but drops the decimal part, returning only the whole number. That's why10 // 3results in3. - The modulus operator (
%) gives you the remainder of a division. For instance,10 % 3evaluates to1, which is what's left over.
Using built-in functions with int
numbers = [5, -10, 15, -20]
print(f"Absolute value: {abs(-42)}")
print(f"Maximum: {max(numbers)}")
print(f"Minimum: {min(numbers)}")
print(f"Power: {pow(2, 8)}")--OUTPUT--Absolute value: 42
Maximum: 15
Minimum: -20
Power: 256
Python offers several built-in functions that simplify common integer manipulations. They're efficient and help keep your code concise.
- The
abs()function returns the absolute value of a number, which is its distance from zero. For example,abs(-42)gives you42. - You can use
max()andmin()to find the largest and smallest values within a collection of numbers, like the listnumbers. pow()is used for calculating exponents.pow(2, 8)is equivalent to 2 to the power of 8, resulting in256.
Advanced integer techniques
Beyond everyday arithmetic, integers offer powerful, low-level control for tasks like bitwise manipulation, working with different number bases, and handling exceptionally large values.
Bitwise operations with integers
a = 60 # 0011 1100
b = 13 # 0000 1101
print(f"AND: {a & b}")
print(f"OR: {a | b}")
print(f"XOR: {a ^ b}")
print(f"Left shift: {a << 2}")
print(f"Right shift: {a >> 2}")--OUTPUT--AND: 12
OR: 61
XOR: 49
Left shift: 240
Right shift: 15
Bitwise operations manipulate the individual bits of an integer's binary representation. They're great for performance-critical tasks or low-level data manipulation, like working with hardware or network protocols.
- The logical operators
&(AND),|(OR), and^(XOR) compare the bits of two numbers. For example,a & bresults in12because it keeps only the bits that are1in both60and13. - The shift operators,
<<and>>, move bits left or right. This provides a fast way to multiply or divide by powers of two.
Working with different number bases
decimal = 42
print(f"Binary: {bin(decimal)}")
print(f"Octal: {oct(decimal)}")
print(f"Hexadecimal: {hex(decimal)}")
print(f"Convert from hex: {int('2A', 16)}")--OUTPUT--Binary: 0b101010
Octal: 0o52
Hexadecimal: 0x2a
Convert from hex: 42
Python simplifies working with different number systems, which is useful in areas like computer graphics or networking. You can easily convert a decimal integer into its binary, octal, or hexadecimal string representation.
- The functions
bin(),oct(), andhex()handle these conversions, adding prefixes like0band0xto the output to indicate the base. - To convert back, you can use the
int()function with a second argument specifying the base, such asint('2A', 16)to parse a hexadecimal string.
Handling very large integers
factorial_20 = 2432902008176640000
large_power = 2 ** 100
print(f"20! = {factorial_20}")
print(f"2^100 = {large_power}")
print(f"Digits in 2^100: {len(str(large_power))}")--OUTPUT--20! = 2432902008176640000
2^100 = 1267650600228229401496703205376
Digits in 2^100: 31
Python's integers automatically handle numbers of any size, limited only by your system's memory. This is a major advantage over languages with fixed-size integers, as you don't need to worry about overflow errors when dealing with massive calculations.
- The code demonstrates this by effortlessly storing huge values like
factorial_20and the result of2 ** 100. - You can even perform operations on them, such as finding the number of digits by converting the integer to a string and checking its length with
len().
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the integer techniques covered in this article, Replit Agent can turn them into production tools:
- Build a number base converter that translates values between decimal, binary, and hexadecimal using functions like
bin()andint(). - Create a bitwise operation calculator that visualizes how operators like
&,|, and<<manipulate data at the bit level. - Deploy a large-number utility for cryptographic or scientific tasks that leverages Python's ability to handle arbitrarily large integers.
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser. It's a faster way to bring your concepts to life.
Common errors and challenges
While integers are straightforward, you'll likely encounter a few common pitfalls, especially with type conversions and division operations.
- When converting strings with
int(), you'll get aValueErrorif the string contains non-numeric characters or a decimal point. To avoid a crash, you can wrap the conversion in atry-exceptblock, which lets you catch the error and handle it gracefully. - Dividing by zero is a mathematical impossibility, and Python will raise a
ZeroDivisionErrorif you try. This applies to both the/and//operators. Always check if your divisor is non-zero with anifstatement before performing the division. - Using the wrong division operator can introduce subtle bugs. Standard division (
/) always returns a float, while integer division (//) truncates the result to an integer. If your logic requires a whole number, using/by mistake can lead to unexpected behavior, so be sure to use//.
Handling ValueError when converting strings to int
A frequent challenge is converting a string to an integer when the string contains non-digit characters. Python's int() function can't parse it, so it raises a ValueError, which will stop your program if unhandled. The code below shows this error in action.
user_input = "42a"
number = int(user_input) # This will raise ValueError
print(f"The number is: {number}")
Here, the int() function receives "42a", but it can't convert the non-numeric character 'a'. This conflict raises a ValueError. The next snippet shows how to anticipate and manage this kind of error.
user_input = "42a"
try:
number = int(user_input)
print(f"The number is: {number}")
except ValueError:
print(f"Cannot convert '{user_input}' to an integer")
The solution wraps the risky conversion in a try-except block. Python first attempts the code in the try block. If it fails with a ValueError, the program doesn't crash; it jumps to the except block and runs that code instead. This is a robust way to handle unpredictable input, like data from users or files, preventing your application from stopping unexpectedly. It's a fundamental pattern for writing resilient code.
Avoiding division by zero errors
Dividing by zero is a mathematical impossibility, and Python enforces this by raising a ZeroDivisionError. This error, which occurs with operators like //, will stop your program. The code below shows this scenario in action with a denominator of zero.
numerator = 100
denominator = 0
result = numerator // denominator # ZeroDivisionError
print(f"Result: {result}")
The code assigns 0 to the denominator variable. When the expression numerator // denominator is evaluated, it attempts to divide by zero, which is an invalid operation. The next snippet shows how to guard against this error.
numerator = 100
denominator = 0
if denominator != 0:
result = numerator // denominator
print(f"Result: {result}")
else:
print("Cannot divide by zero")
The solution is to check the denominator before you divide. The code uses an if denominator != 0: condition to guard the operation. If the condition is met, the division proceeds safely. Otherwise, the else block executes, printing a message and preventing the ZeroDivisionError. It's a crucial check whenever a divisor's value is uncertain, especially when it comes from user input or the result of another calculation.
Using correct division operator for integer results
A subtle but common bug arises from using the wrong division operator. Python's standard division (/) always produces a float, even if the inputs are integers. This can cause issues when your logic expects a whole number. The code below demonstrates this.
total_items = 5
people = 2
items_per_person = total_items / people # Returns 2.5
print(f"Each person gets {items_per_person} items")
Using the standard division operator / results in 2.5, which doesn't make sense for indivisible items. See how to adjust the code to get the expected whole number result in the next snippet.
total_items = 5
people = 2
items_per_person = total_items // people # Integer division: 2
remainder = total_items % people # Remainder: 1
print(f"Each person gets {items_per_person} items, with {remainder} left over")
The solution uses the integer division operator (//) to ensure the result is a whole number. It's crucial when your logic depends on integer outcomes, like distributing indivisible items. The code also uses the modulus operator (%) to find the leftover items. You should watch for this issue whenever you divide numbers but need to discard the fractional part, as standard division (/) will always produce a float, which can introduce unexpected behavior in your program.
Real-world applications
Beyond the technical details and error handling, integers power practical applications for tasks like managing budgets or creating simple ciphers.
Using int for budget calculations
Integers make budget tracking straightforward, as you can represent income and expenses as whole numbers, total your spending with sum(), and calculate your savings.
# Monthly budget tracking
income = 3000
expenses = [450, 700, 200, 150, 350]
total_expenses = sum(expenses)
savings = income - total_expenses
print(f"Income: ${income}")
print(f"Total expenses: ${total_expenses}")
print(f"Savings: ${savings}")
print(f"Percentage saved: {(savings * 100) // income}%")
This snippet models a simple budget by storing individual costs in an expenses list. It then uses the sum() function to efficiently add up all items in the list, providing a clean way to calculate total_expenses.
The final line calculates the percentage saved. It's a practical choice to use the integer division operator // to ensure the result is a whole number, which avoids decimals in the final output. This approach shows how integers and built-in functions work together for clear financial calculations.
Implementing a simple cipher with int operations
int operations are also perfect for building a simple cipher, where you can shift the numeric value of each character to encrypt a message.
message = "hello"
encrypted = ""
decrypted = ""
# Simple encryption: shift ASCII value by 5
for char in message:
encrypted += chr(ord(char) + 5)
# Decryption
for char in encrypted:
decrypted += chr(ord(char) - 5)
print(f"Original: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
This snippet creates a simple substitution cipher by manipulating character codes. It loops through the message, converting each character into its underlying integer representation with the ord() function. This allows you to perform arithmetic directly on the text data.
- For encryption, it adds
5to each character's integer value and useschr()to turn the new number back into a character, building theencryptedstring. - Decryption reverses the process by subtracting
5from each encrypted character's value, restoring the original message.
Get started with Replit
Turn what you've learned into a real tool. Just tell Replit Agent what to build, like “create a number base converter” or “build a simple cipher tool using character code shifts.”
The agent writes the code, tests for errors, and deploys your app automatically. Start building with Replit and see your idea go live.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)
.png)
.png)