HOWTO · Python
How to Solve the TypeError: An Integer Is Required in Python
This tutorial discusses the TypeError: an integer is required in Python, exploring its causes and providing effective solutions. Learn how to use type casting, input validation, and try-except blocks to resolve this common error. Enhance your Python skills and improve your coding practices with our easy-to-follow guide.
On this page
The TypeError: an integer is required message appears when Python code hands a function a value of the wrong type: the function asked for an integer and received something else, usually a string. It shows up in loops that feed string characters into chr(), in settings passed as text instead of numbers, and in countless similar calls.
This guide explains what the message actually means, how to find the value that caused it, and how to pick the fix that matches what you intended the code to do.
What “TypeError: an integer is required” means
A TypeError with this wording reports a single failed argument: a function or method declared that one of its parameters must be an integer — a Unicode code point, a count, a maximum length, a file mode — and the value it received was not one. The check happens when the call is parsed, so the function fails before doing any work.
Python spells this same failure in a few ways depending on which function raises it and which version you run. You may see an integer is required, an integer is required (got type str), or 'str' object cannot be interpreted as an integer. All three are TypeError, and all three mean the same thing: the argument’s type did not match the parameter’s requirement.
Do not confuse this with the unsupported operand type(s) family of messages. An expression like "10" + 5 raises TypeError: can only concatenate str (not "int") to str, which describes two operands that cannot be combined — a different diagnostic with a different fix, even though it is also a TypeError.
Why this error occurs
Built-in functions and the C-implemented parts of the standard library parse their arguments strictly. When the parser finds a string where an integer is required, the call stops immediately. A minimal trigger is the maxlen parameter of collections.deque, which must be an integer:
from collections import deque
try:
queue = deque([], "3")
except TypeError as error:
print(f"{type(error).__name__}: {error}")
TypeError: an integer is required
A more common way to hit the same mistake is calling chr() inside a loop over a string. Iterating a string yields one-character strings, but chr() maps an integer code point to a Unicode character, so each character the loop produces is rejected:
try:
for char in "42":
print(chr(char))
except TypeError as error:
print(f"{type(error).__name__}: {error}")
TypeError: 'str' object cannot be interpreted as an integer
Same class of bug, different wording. In both cases the fix starts the same way: find the argument that is not an integer.
How to diagnose the value passed to the function
Read the traceback from the bottom up. The last line names the exception type and message; the line just above it shows the call that failed. From there, trace the argument back to where it came from — a loop variable, input(), a config file, or a JSON string field — because values read as text arrive as strings, while parsed formats such as JSON can already yield typed values.
When the message does not name the value you passed, inspect it at the call site by printing repr() and type():
for char in "42":
print(f"{char!r} has type {type(char).__name__}; its code point is {ord(char)}")
'4' has type str; its code point is 52
'2' has type str; its code point is 50
Now the mismatch is visible: the loop hands chr() the string '4' (type str), while ord() reveals the integer it actually works with — the code point 52. Once you can name the argument’s real type and value, choosing the right fix is straightforward.
How to fix the input safely
Match the fix to what you intended:
- To print digits or characters from a string, print the value directly —
print(char)needs nochr()call at all. - To get the character stored at a given code point, pass
chr()a real integer.ord()returns the code point of a character, andint()converts a string of digits into the number it names. Run this example:
for char in "42":
print(char, "->", chr(ord(char)))
4 -> 4
2 -> 2
For parameters like maxlen that come from a config file or command line, convert the text once with int() before the call and pass the result.
int() only accepts strings that look like whole numbers. For untrusted input, check it first with str.isdigit() so a bad value never reaches the conversion:
text = "53"
if text.isdigit():
print(chr(int(text)))
else:
print("not a whole number")
5
When a check is not enough, handle the conversion failure directly. int() on an unsuitable string raises ValueError, a different exception from the TypeError you started with:
try:
number = int("10.5")
except ValueError as error:
print(f"{type(error).__name__}: {error}")
ValueError: invalid literal for int() with base 10: '10.5'
Verify the fix and avoid related type errors
Re-run the code and read the last line of any remaining traceback — it tells you whether you still have a type problem or have moved on to a different bug. With maxlen passed as an integer, the earlier failure becomes a working deque:
from collections import deque
queue = deque(["x", "y", "z"], maxlen=3)
queue.append("w")
print(list(queue))
['y', 'z', 'w']
Keep these points in mind:
- Match each argument’s type to the signature:
chr()takes an integer code point,ord()takes a character, andint()turns a numeric string into an integer. - A
ValueErrorfromint()is not theTypeErroryou started with — catching one will not hide the other, so handle each at its own source. - Messages like
can only concatenateorunsupported operand type(s)describe mixing types in an expression, not a bad argument; they need a different fix.
The error is a signpost, not a dead end: once you know which value carried the wrong type, the correct conversion — or no conversion at all — usually follows directly.