Here's a the problem we want to solve: we want to find if the string s contains a string consisting of exactly $n$ "a"s followed by one "b". ($n+1$ "a"s followed by one "b" would count, and $n$ "a"s followed by "bb" won't count either.)
The approach we'll take is defining the state variable cur_run_a (Note: it's just a regular integer. We just call it a state variable), and make sure that it's up-to-date at every iteration.
def n_as_plus_b(s, n):
cur_run_a = 0 #the length of the current run of a's
for i in range(len(s)):
if s[i] == "a":
cur_run_a += 1
elif s[i] == "b":
if cur_run_a == n:
if i == len(s)-1:
return True
if s[i+1] != "b":
return True
else:
cur_run_a = 0
else:
cur_run_a = 0
return False