To simplify the input:

isbn = [int(input("ISBN character {0}: ".format(i))) 
        for i in range(1, 11)] # or 'format(i+1)' and 'range(10)'

This uses a list comprehension to simultaneously loop and built the list of integers.

Alternatively, take the whole input at once and convert it into individual integers:

isbn = list(map(int, input("Enter ISBN: ")))

Here map applies int() to convert each of the characters in the input string in turn.

Answer from jonrsharpe on Stack Overflow
Top answer
1 of 3
1

You need to open the file properly (use the open file object and the csv module to parse the comma-separated values), read each row and convert the strings into float numbers, then apply the correct formula:

import math, csv

fname = '\\pathname\\GerrysTenHz.txt'
magn1 = []

with open(fname, 'rb') as inputfile:
    reader = csv.reader(inputfile)
    for row in reader:
        magn1.append(math.sqrt(sum(float(c) ** 2 for c in row)))

which can be simplified with a list comprehension to:

import math, csv

fname = '\\pathname\\GerrysTenHz.txt'

with open(fname, 'rb') as inputfile:
    reader = csv.reader(inputfile)
    magn1 = [math.sqrt(sum(float(c) ** 2 for c in row)) for row in reader]

The with statement assigns the open file object to inputfile and makes sure it is closed again when the code block is done.

We add up the squares of the column values with sum(), which is fed a generator expression that converts each column to float() before squaring it.

2 of 3
0

You need to use the lines of the file and the csv module (as Martijn Pieters points out) to examine each value. This can be done with a list comprehension and with:

with open(fname) as f:
        reader = csv.reader(f)
        magn1 = [math.sqrt(sum(float(i)**2 for i in row)) for row in reader]

just make sure you import csv as well


To explain the issues your having (there are quite a few) I'll walk through a more drawn out way to do this.

you need to use what openreturns. open takes a string and returns a file object.

f = open(fname)

I'm assuming the range in your for loop is suppose to be the number of lines in the file. You can instead iterate over each line of the file one by one

for line in f:

Then to get the numbers on each line, use the str.split method of to split the line on the commas

    x, y, z = line.split(',')

convert all three to floats so you can do math with them

    x, y, z = float(x), float(y), float(z)

Then use the ** operator to raise to a power, and take the sqrt of the sum of the three numbers.

    n = math.sqrt(x**2 + y**2 + z**2)

Finally use the append method to add to the back of the list

    Magn1.append(n)
Discussions

For loop gives me a type error, can someone explain why?
for I in range (0, 11(sunsports)): This syntax is wrong. 11 is a int object and the () indicates a call. So Python things your trying to call an int object. Seems that you want to loop over the list from index 0 to 11 for element in sunspots_19[0:11]: More on reddit.com
๐ŸŒ r/learnpython
4
2
August 21, 2022
python - Why am I getting a TypeError when looping? - Stack Overflow
I'm working on a Python extension module, and one of my little test scripts is doing something strange, viz.: x_max, y_max, z_max = m.size for x in xrange(x_max): for y in xrange(y_max): ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
TypeError in Python Programming - Stack Overflow
I wrote the following program for square each digit of a number. But, it is showing an error as "int" object is not iterable. def square_digits(num): a = 1 for i in num: a = i * i ret... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Getting a TypeError after one iteration of a loop? - Stack Overflow
As mentioned in the title I am getting a TypeError: 'float' object is not callable when using my code. The code runs once correctly with the information that I want but fails to run the second time... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ int-object-is-not-iterable-python-error-solved
Int Object is Not Iterable โ€“ Python Error [Solved]
March 24, 2022 - If you are trying to loop through an integer, you will get this error: count = 14 for i in count: print(i) # Output: TypeError: 'int' object is not iterable ยท One way to fix it is to pass the variable into the range() function.
๐ŸŒ
PyTutorial
pytutorial.com โ€บ python-typeerror-causes-and-fixes
PyTutorial | Python TypeError: Causes and Fixes
April 23, 2026 - TypeError: list indices must be integers or slices, not str ยท For lists, always use integer indices. If you need to access by key, use a dictionary instead. Using a for loop on an integer or a non-iterable object raises a TypeError.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ for loop gives me a type error, can someone explain why?
r/learnpython on Reddit: For loop gives me a type error, can someone explain why?
August 21, 2022 -

I've tried a few different things to get the for loop to work, but I'm not sure how to explain properly, since I'm new to python. Could someone point me in the right direction to fix this? I'm trying to get the for loop to add a 0 to index 0 of the data array until it reaches index 11. Thanks :)

#d shifted data for 12 months
y=1801 
m=1 
sunspots_index(y,m)
lower_bound = sunspots_index(y,m)-1 
y=1900
m=1 
sunspots_index(y,m)
upper_bound = sunspots_index(y,m)-1

sunspots_19s = data[lower_bound:upper_bound]
print(sunspots_19s)

for i in range (0,11(sunspots_19s)):
    sunspots_19s_shifted = np.insert(sunspots_19s_shifted,0,0)


sunspots_19s_shifted

error msg:

[40.1 27.  29.  ...  8.4 13.   7.8]
<>:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
<>:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
/var/folders/gx/1dv83d1n40lgf3pvqlt2j8sh0000gn/T/ipykernel_778/3474559538.py:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
  for i in range (0,11(sunspots_19s)):
/var/folders/gx/1dv83d1n40lgf3pvqlt2j8sh0000gn/T/ipykernel_778/3474559538.py:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
  for i in range (0,11(sunspots_19s)):
/var/folders/gx/1dv83d1n40lgf3pvqlt2j8sh0000gn/T/ipykernel_778/3474559538.py:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
  for i in range (0,11(sunspots_19s)):
/var/folders/gx/1dv83d1n40lgf3pvqlt2j8sh0000gn/T/ipykernel_778/3474559538.py:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
  for i in range (0,11(sunspots_19s)):
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [209], in <cell line: 17>()
     12 print(sunspots_19s)
     14 xxx=11
---> 17 for i in range (0,11(sunspots_19s)):
     18     sunspots_19s_shifted = np.insert(sunspots_19s_shifted,0,0)
     21 sunspots_19s_shifted

TypeError: 'int' object is not callable
๐ŸŒ
Medium
medium.com โ€บ @rayancrazer โ€บ type-error-in-python-75680deaef26
Understanding and Resolving Type Errors in Python
November 24, 2024 - 3. Using an object of the wrong type in a loop In this example, we are trying to iterate over a string using a โ€œforโ€ loop, but we have accidentally used an integer instead of a string.
๐ŸŒ
Sdsu
gawron.sdsu.edu โ€บ python_for_ss โ€บ course_core โ€บ book_draft โ€บ programming_intro โ€บ loops.html
4.4. Loops โ€” python_for_ss 0.1.1 documentation
Let x be the first thing in the ... try to loop through an integer, as in the following silly code snippet: 1>>> for x in 1: 2 print x 3Traceback (most recent call last): 4 .... 5TypeError: 'int' object is not iterable ยท This is also the error that occurs if we try to assign something that ...
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 2685565 โ€บ why-am-i-getting-a-typeerror-when-looping
python - Why am I getting a TypeError when looping? - Stack Overflow
I'm working on a Python extension module, and one of my little test scripts is doing something strange, viz.: x_max, y_max, z_max = m.size for x in xrange(x_max): for y in xrange(y_max): for z in xrange(z_max): #do my stuff ยท What makes no sense is that the loop gets to the end of the first 'z' iteration, then throws a TypeError, stating that "an integer is required".
Top answer
1 of 2
2

You're looking for the range(num) function.

You probably also want to use a list (denoted by [brackets, and, commas]).

Try this for example:

my_list = [] # empty list
for char in 'aword':
    my_list.append(char * 2)
print(my_list)

Or to be really pythonic you can step through the data and create your list at the same time with a list comprehension. Think of it like an in-line for loop that returns a list:

result = [char * 2 for char in 'aword']
print(result)

The first part (char * 2) tells what you want in each entry of the list. In your case that would be a squaring operation on some source data. The second part (for char in 'aword') tells you where to get the source data from. In your case it would be range(num).

2 of 2
1

first off, this is how to fix your code:

If you want a list of squared numbers beginning from 1 to num:

`
def square_digits(num):
    # initialize an empty list
    a = []
    # why num + 1 when you want numbers until num? check out this link for an explanation
    # on how to use and the different uses of the range() function
    # http://pythoncentral.io/pythons-range-function-explained/
    for i in range(1, num + 1):
        # square the numbers beginning from 1,
        squared_i = i * i
        # and then add the result to the list that we have
        a.append(squared_i)
    # after everything is done, return the list
    return a

result = square_digits(12)
print(result)
`

In your earlier example, you were basically trying to make this work:

`
for i in 12:
    square_result = i * i
    print ("the square of " + str(i) + " is " + str(square_result))
`    

which isn't going to work because you're trying to iterate on 12, which is an int

However if you do this:

`
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]:
    square_result = i * i
    print ("the square of " + str(i) + " is " + str(square_result))
`    

then you're going to have better results, because you're iterating on a list.

the shorter way of doing the above example is:

`
num = 12
for i in range(1, num + 1):
    square_result = i * i
    print ("the square of " + str(i) + " is " + str(square_result))
`    

which should also work because range(1, num + 1) should return the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] if num = 12 in python2. In python3 however, the range function will not return a list, instead it will return something that can be iterated upon like a list for the purpose of this question.

However, I'm not certain if it's a list your looking for as a result, if not, feel free to clarify your question, hopefully others can also chime in.

๐ŸŒ
Rollbar
rollbar.com โ€บ home โ€บ how to fix typeerror: int object is not iterable in python
How to Fix TypeError: Int Object Is Not Iterable in Python
In Python, looping through an object requires the object to be โ€œiterableโ€. Since integers are not iterable objects, looping over an integer raises the TypeError: 'int' object is not iterable exception.
Published: 1 week ago
Top answer
1 of 2
15

What is a TypeError?

It means exactly what it sounds like: there is an Error that is caused by the Type of one or more of the values in the code.

... but what is a "type"?

In a Python program, every object has a type. By "object" (equivalently in Python, "value") we mean something that can be given a name in the source code. Most names are simple variables: if we write x = 1, then 1 is an object, it has a name x, and its type is int - the type itself has a name.

"Type" means more or less what it sounds like: it tells you what kind of thing something else is. 1, 2 and 3 are all integers; they have the same type, int. You can think of it as representing the concept of an integer.

Not every type has a built-in name. For example, functions are objects (most other languages don't work this way!), and they have a type, but we can't directly refer to that type by name in our code.

Every type does have a representation as an object, however, whether it's named or not. You can use the built-in type to get such a "type object":

>>> type(1) # the result from this...
<class 'int'>
>>> int # is the same:
<class 'int'>
>>> type(int) # We can look a bit deeper:
<class 'type'>
>>> def func():
...     pass
>>> type(func) # and get types that aren't named:
<class 'function'>
>>> type(type) # and there's this special case:
<class 'type'>

Notably, the type of type is type itself.

You may notice that Python (3.x) displays these type objects with the word class. This is a useful reminder: when you create a class, you are defining a new type of data. That is the purpose of classes.

What do messages like this mean?

We can break the examples down into a few categories:

TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments

These exceptions are telling you that the arguments (the things you put between the ()) for calling func (or creating an instance of MyClass) are wrong. Either there are too many, not enough, or they are not properly labelled.

This is admittedly a little confusing. We're trying to call a function, and the thing we're calling is a function - so the type does actually match. The identified problem is with the number of arguments. However, Python reports this as a TypeError rather than a ValueError. This might be in order to look more familiar to programmers from other languages such as C++, where "types" are checked at compile time and can be very complex - such that functions that accept different types or numbers of arguments, are themselves considered to have different types.

TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str (not "int") to str
TypeError: '>' not supported between instances of 'int' and 'str'
TypeError: can't multiply sequence by non-int of type 'float'
TypeError: string indices must be integers

These exceptions are telling you that the left-hand side and right-hand side of an operator (a symbol like + or > or ^, used to compute a result) don't make sense. For example, trying to divide or subtract strings, or repeat a string a non-integer number of times, or (in 3.x) compare strings to numbers. As a special case, you can use + between two strings (or lists, or tuples), but it doesn't "add" them in a mathematical sense. If you try to use + between an integer and a string, the error message will be different depending on the order.

TypeError: %d format: a number is required, not str
TypeError: not all arguments converted during string formatting

These ones are a bit tricky. The % operator is used to get the modulus (remainder when dividing numbers), but it can also be used to format strings by replacing some placeholders. (This is an outdated system that's hard to get right and has weird special cases; in new code, please use f-strings or the .format method.)

An error occurs because the placeholders in the string on the left-hand side don't match up with what's on the right-hand side. In the second case, it's likely that you actually wanted to calculate a modulus, so the left-hand side should be a number (most likely an integer) instead. It's debatable whether these should be ValueErrors instead, since it could be that the contents of the string are wrong. However, Python cannot read your mind.

TypeError: list indices must be integers or slices, not str

This is also a problem with an operator, this time the [] operator (used for indexing into a list, slicing a list, or looking up a key in a dictionary). A string makes sense inside the [] if we are looking up a key in a dictionary that has strings as keys; but we cannot index into a list with it.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
TypeError: a bytes-like object is required, not 'str'
TypeError: bad operand type for abs(): 'str'

These mean that something wrong was passed to a built-in function (or another callable, such as a type). Functions that you get from a library may raise their own TypeErrors with custom messages. The message should be pretty straightforward.

TypeError: descriptor 'to_bytes' for 'int' objects doesn't apply to a 'str' object

This one is very unusual, and most people who ask this question would never run into it (except maybe with the datetime standard library module). It happens because of trying to use a method as if it were a function, but giving it the wrong type of thing for self: for example, int.to_bytes('1'). The code is wrong because '1' is a string, and strings don't support .to_bytes. Python will not convert the string to integer; and it cannot give an AttributeError instead because to_bytes was looked up in the class, not on the string.

TypeError: 'int' object is not iterable
TypeError: cannot unpack non-iterable int object
TypeError: 'int' object is not callable
TypeError: 'int' object is not subscriptable

These mean exactly what they sound like. "iterable" means "able to be iterated"; i.e., checked repeatedly to get separate values. This happens in for loops, comprehensions and when trying to convert to list etc. The "unpack" variation of the message results from trying to use unpacking syntax on the non-iterable.

"callable" means "able to be called"; to "call" something is to write () after it (possibly with arguments between the ()). Code like 1('test') doesn't make sense because 1 isn't a function (or a type).

"subscriptable" means "able to be subscripted"; here, "subscripting" means either using slice syntax (x[1:2:3]), or indexing or looking for a key (x['test']). We can only do this with sequences (like lists or strings) and mappings (like dicts).

2 of 2
8

How can I understand and fix the problem?

First, look at the traceback to see where in the code the error occurs. If it's in a library, work backwards to the point where your code uses the library. Then read the error message carefully, and compare it to the code, to figure out what causes the complaint. Finally, think carefully: is the operation wrong, or the values?

Examples

(TODO)

Some non-obvious things

Reusing names

Did you perhaps reassign the name of a built-in callable, such as str or input or list? Did you try to reuse a name for two different things (for example, a function and some global data that it uses)?

Names in Python can only refer to one thing at a time. If you use, say, list as a variable name, then it isn't also the name of "the abstract concept of a list" any more, so you can't use it to create more lists (which includes converting other things to lists). If you create a global variable months with a list of strings, and then write a function months, the function replaces the list, and the function's code can't look up the list. This can easily happen accidentally when using from some_module import * syntax.

Similarly, if you try to make a class that uses the same name for an method as for a data attribute of the instances, that will cause the same problem. (There's also a tricky special case with @staticmethod).

Processing lists

Sometimes people expect to be able to use a list like a Numpy array, and "broadcast" an operation or a function call to each element of the list. That doesn't work. Use a list comprehension instead.

Handling None

Consider whether you need to handle None as a special case. But try to avoid getting into that situation in the first place; "special cases aren't special enough to break the rules", as they say.

Trying to use a library (including a standard library)

If something doesn't work like you'd expect (for example, trying to subtract datetime.times or serialize an instance of a user-defined class as JSON) - rather than trying to treat the problem as a debugging question, search for solutions for what you want that part of the code to do.

If the error mentions a 'str' type and you thought it should be a number

Did you get it from the input function? That gives you a str, even if it looks like a number. Please see How can I read inputs as numbers?.

If the error mentions a 'function' type or 'type' type

Did you forget to call the function, or create an instance of a class?


Error messages about wrong arguments

The error message will tell you the name of the function; so look at the part of the line that calls that function, and check the arguments. Is there a correct number of positional arguments? Is there a keyword argument that must be provided, and is missing? Is there a keyword argument that shouldn't be provided? Is there a positional argument that is also provided by keyword?

If you are writing a method for a class, remember to allow for self. It is necessary for instance methods. If you are calling a method, keep in mind that self will be counted as an argument (both for the amount "required" and the amount "given").

A common beginner error is attempting to use a method (which isn't a classmethod) from a class without instantiating it. You'd do something like

value = MyClass.method(things)

where you should be doing something like

instance = MyCLass()
value = instance.method(things)

which (obscurely) passes instance as the first (self) argument to method, and things as the second argument.

If you are using a callback that takes arguments from an indirect source, check the source.

If you are trying to create an instance of your own class, and get an TypeError from __init__, make sure that you actually wrote an __init__.

If you don't know what the arguments should be, check the documentation. If the arguments make sense, maybe the function is wrong - make sure you didn't confuse it for another one in the same library.

Error messages about operand types

Make sure the operator is correct for what you want the code to do (for example: ^ is not exponentiation; you want **), and then check the operand types.

In most cases, it will be appropriate to convert the type - but think carefully. Make sure the operation will make sense with the new types. For example, if the code is l + 'second', and l is a list that currently contains ['first'], chances are good we don't want to concatenate strings, but instead create a modified list that also has 'second' as an element. So actually we wanted to "add" another list: l + ['second'].

If string indices must be integers, it could be that the string being indexed is JSON or something of that sort, which should have been parsed already to create a dictionary (possibly with nested lists and dictionaries).

If list indices must be integers or slices, it's likely that the problem is with the list, rather than the index. If you expected the list to be a dict, check whether it contains a dict - especially if it contains exactly one element, which is a dict. Then check if that's the dict that should actually be looked into. If so, the solution is easy: simply add another level of indexing, in order to grab that dict first. This commonly happens when trying to grab data from parsed JSON.

Error messages about string formatting

Seriously, did you intend to do string formatting? If you do want to format a string, consider using f-strings or the .format method - these are easier to debug, and have fewer special cases. But more likely, the left-hand side is some string like '1' that should have been converted to int (or maybe float) first.

Error messages about a "descriptor"

Python's error message here is fairly cryptic - it's using terminology that most programmers rarely if ever have to worry about. But once recognized, the error is very easy to pattern-match. Take special care if the class can be instantiated with no arguments - an empty pair of parentheses () is still necessary to instantiate the class; otherwise, the code refers to the class itself. An instance is required in order to use methods.

Custom error messages from built-in functions

A "bad operand" for a "unary" operator (for example bad operand type for unary +: 'str') can be caused by a stray comma. 'a', + 'b' is not the same as 'a' + 'b'; it is trying to use + as a unary operator on the 'b' string, and then make a tuple. (You know how you can write e.g. -1 to get a negative number? The - there is a unary operator. It turns out you can similarly write +1; it means the same as 1, of course.)

Especially if you have had to migrate code from 2.x to 3.x, be very careful about the distinction between bytes and str types in 3.x. bytes represents raw data; str represents text. These are fundamentally different and unrelated things, and it is only possible to convert from one to the other by using an encoding. In Python 3.x, files that are opened in a binary mode (using 'b' in the mode string) produce bytes when read, and must be given something compatible with bytes when written to. str does not qualify; you must specify an encoding explicitly. The canonical for this problem is "TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3.

Error messages where something "is not" usable in some way

Did you want to use it that way?

Python can't read your intent. For example, accessing an element of a list is done using [], not (). If the code says () instead, that will be interpreted as an attempt to call the list, so the error message will complain that the list is not callable.

Not iterable

When something is not iterable, the problem is very likely with the thing, rather than the iteration. If you want a for loop to run a specific number of times, you still need something to iterate over; a range is the usual choice. The same is true if you are using a list comprehension etc. to make multiple copies of a value. If you have an integer x and you want to make a list with one item, which is that integer, that is spelled [x], not list(x).

It's especially common to see 'NoneType' object is not iterable. There is exactly one 'NoneType' object: the special value None - Python forbids creating any more instances of that class. Python methods that work in-place - especially list methods - generally return None rather than the list that was modified. See also TypeError: 'NoneType' object is not iterable in Python.

Not callable

If a 'module' object is not callable, it's most likely because you want a function or class from the module, that has the same name as the module, rather than the module itself. The linked example is for the socket standard library; other common cases include datetime and random.

Also make sure that the code doesn't call a function and remember the result, instead of remembering the function itself. This is a common problem with APIs that expect a "callback" function. (If you need to choose the arguments ahead of time, but not actually call the function, see How can I bind arguments to a function in Python? .) Sometimes people also try to provide the name of a function as a string, rather than providing the function itself.

Beginners sometimes expect to be able to do "implicit multiplication" in a mathematical formula, the way that it works in math class. In a Python program (like other popular languages), code like a(b + c) does not multiply the integer a by the result of b + c; it attempts to call a as if it were a function. See Why do I get "TypeError: 'int' object is not callable" from code like "5(side_length**2)"?.

Not subscriptable

Sometimes, people try to get "digits" from a number by indexing into it as if it were a string. int and float values aren't strings; they don't have digits in them. So this will cause a "is not subscriptable" TypeError. The numeric value is the same no matter what base you write them in, and there are other ways to write a number besides base ten; so it is your responsibility to create the appropriate string first.

If you are trying to work with nested lists, be careful about indexing into them. A list like example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] should be indexed like example[i][j], not e.g. example[i[j]]. The logic here should be pretty simple: the correct code means to index into example (getting a list of integers), and then index into that result. The incorrect code means to use j as an index into i first, because of how the brackets are nested.

If you are trying to call a function or use a class (such as the built-in range), remember that this uses parentheses, not square brackets:

# WRONG
range[10]
# RIGHT
range(10)
Top answer
1 of 2
1

I understand what you're trying to do, but your Python code won't do it and definitely throw an Error, instead try this simplified code:

# Get string from user
string = input("Enter a phrase: ")
doubleOccurrences = ""

# loop through the string, which checks if two consecutive characters match
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        doubleOccurrences += string[i] * 2
# print the output
print("Your input contains the following double occurrences:", doubleOccurrences)

To explain this code, we take input of user and store it in string, then set doubleOccurences to empty string, then we loop through 0 to len(string) - 2 inclusive (notice that character at position len(arr) - 1 doesn't have a next character after it to check for!), then we check if condition satisfied we add 2 times the character to doubleOccurrences doubleOccurrences += string[i] * 2 then finally print the result.

2 of 2
0

When you do for i in string: you are basically overwriting your i variable with the string iterator for the variable 'string'. This means you are iterating through each letter in the string and storing the character in "i". The correct way to go about this would be to use enumerate. You can also use range like this range(len(string)). Here is a working example of what you are trying to do:

string = str(input("Enter a phrase: "))

doubleOccurrences = str("N/A")

#loop through the string, which checks if two consecutive characters match
for i in range(len(string)):
    for j in range(i + 1, len(string)):
        if string[i] == string[j]:
            doubleOccurrences = doubleOccurrences.replace("N/A","")
            doubleOccurrences = (doubleOccurrences + string[i] + string[j])
        else:
            doubleOccurrences = doubleOccurrences

#print the output
print("Your input contains the following double occurrences: " + doubleOccurrences)

Note that I am unsure what you are trying to do exactly, so I did not make sure that the result was the right result, I only made sure that it runs. I also had to modify some of your logic, as you are not accounting for 'j' going out of bounds. Using a double for loop will avoid this issue.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ handling-typeerror-exception-in-python
Handling TypeError Exception in Python - GeeksforGeeks
August 22, 2025 - a = ["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"] b = [0, 1, "2", 3] # Note: "2" is a string, not an integer for i in range(len(b)): try: print(a[b[i]]) # This will fail when b[i] is a string except TypeError: print("TypeError: Check list ...
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ error-types-in-python
Error Types in Python
>>> '2'+2 Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> '2'+2 TypeError: must be str, not int ยท The ValueError is thrown when a function's argument is of an inappropriate type. ... >>> int('xyz') Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> int('xyz') ValueError: invalid literal for int() with base 10: 'xyz'
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ i-m-getting-a-typeerror-how-do-i-fix-it
How to Fix Python TypeError: Common Examples and Solutions for Uncaught Exceptions โ€” pythontutorials.net
In other words, Python expects a specific type (e.g., an integer, list, or function) but receives something else. ... The error message typically includes details about the conflicting types, making it easier to diagnose. For instance: TypeError: unsupported operand type(s) for +: 'int' and 'str' Letโ€™s explore the most frequent TypeError cases, along with examples, explanations, and fixes.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ controlflow.html
4. More Control Flow Tools โ€” Python 3.14.7 documentation
>>> combined_example(1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: combined_example() takes 2 positional arguments but 3 were given >>> combined_example(1, 2, kwd_only=3) 1 2 3 >>> combined_example(1, standard=2, kwd_only=3) 1 2 3 >>> combined_example(pos_only=1, standard=2, kwd_only=3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only' Finally, consider this function definition which has a potential collision between the positional argument name and **kwds which has name as a key: ... There is no possible call that will make it return True as the keyword 'name' will always bind to the first parameter. For example:
๐ŸŒ
Aimadetools
aimadetools.com โ€บ home โ€บ error fixes โ€บ python typeerror โ€” how to fix common type errors
Python TypeError โ€” How to Fix Common Type Errors
March 20, 2026 - Python is telling you what type it got and what it expected. # โŒ Trying to loop over a number for i in 5: # ๐Ÿ’ฅ int is not iterable print(i) # โœ… Use range() for i in range(5): print(i)