For loop in a function – not iterating through string

I’m looking to take in two strings via user input and to call a function to match each character from the first string to that of the second string, and count them. So String 1 = bad and String 2 = bed would return a count of 2 characters matched

def occurrences(text1, text2):

    count = 0

    for c in firstword :
        if c == secondword :
            count += 1
            return True
    return False


firstword = input("Enter first word")

secondword = input("Enter second word")

occurrences(firstword, secondword) 

Passing the two strings into the function returns false, even if they’re exactly the same word. Just wondering where I’m going wrong with the for loop here, why is the if statement not matching the strings and counting. Thanks

Answer

for c in firstword :
    if c == secondword :

You’re iterating over the first string character by character (for c in firstword), and you match that one character to the entire second string secondword. Not to mention that:

  • you’re using the outer variables firstword and secondword instead of the function parameters text1 and text2
  • your function only returns True or False, at no point does it even attempt to return a count
  • you return True right on the first match, if there ever was one, so it could never progress beyond 1

To compare two strings character by character, you need to iterate both string in parallel. The best way to do that is zip:

count = 0
for c1, c2 in zip(text1, text2):
    if c1 == c2:
        count += 1

Which can be made into a one-liner with sum:

def occurrences(text1, text2):
    return sum(c1 == c2 for c1, c2 in zip(text1, text2))

Silly bonus round, if you want to be really fancy and functional about it:

from operator import eq
from itertools import starmap

def occurrences(text1, text2):
    return sum(starmap(eq, zip(text1, text2)))