This is a exercise for Python, and I am confused about the variable scoping in Python.
“Return True if the given string contains an appearance of “xyz” where
the xyz is not directly preceeded by a period (.). So “xxyz” counts
but “x.xyz” does not.xyz_there(‘abcxyz’) → True
xyz_there(‘abc.xyz’)→ False
xyz_there(‘xyz.abc’) → True”
This is my answer:
def xyz_there(str):
for i in range(len(str)-2):
if str[i]=='.':
i+=1
continue
elif str[i:i+3]=='xyz':
return True
return False
And it is wrong. xyz_there('abc.xyz') → False will always return True. Because the variable i will always be 0,1,2…. And the i+=1 doesn’t mean anything.
Why???
It’s not that you can’t change the value of
i. You can. The trick here is that you are iterating over the contents of the return value ofrange. Each time the loop resets you get the next value from that iterable, it does not increment the value ofito progress the loop.