Search code examples
pythonfor-loopif-statementtypeerror

Python - Why is my code returning a TypeError


I'm new to the world of programming (as you can probably tell by my inefficient code & question).

My code is meant to check whether two subsequent characters in a string are identical. I don't understand why the two dummy variables are triggering a TypeError when being referenced in the if statement (if string[i] == string[j]:). They've been initialized as int - why does python appear to be interpreting this as a str type when being used in an if statement?

Thanks for your time.

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

#initialise i and the empty string doubleoccurrences
i = 0
j = i + 1

doubleOccurrences = str("N/A")

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

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


I was expecting python to interpret

if string[i] == string[j]:

as a check on whether the character at index i is equal to the character at index j, given that both i and j have been initialized as integers.


Solution

  • 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.