What is the purpose of `index +=1`?

In the example given for While Loops—

dog_breeds = [‘bulldog’, ‘dalmation’, ‘shihtzu’, ‘poodle’, ‘collie’]

index = 0
while index < len(dog_breeds):
print(dog_breeds[index])
index += 1

What is the purpose of—

index += 1

We need to be sure that i is constantly changing (increasing) so that the test condition eventually fails, otherwise the loop will run indefinitely (infinite loop). We wouldn’t want that.

8 Likes

dog_breeds = [‘bulldog’, ‘dalmation’, ‘shihtzu’, ‘poodle’, ‘collie’]
for dog_breeds
i got an error is If i used a single ’ quote.

it work with " double quote.

Sorry I still dont get this can you elaborate a bit further please.

Every loop needs to stop at some point, for this example it is going to happen when index exceeds.

index =+ 1 means, index = index + 1.

If we want to reach that point we need to bring the ‘index’ value to that level by adding 1 in every iteration by index =+ 1.

1 Like

so we can write it both ways? i+=1 and i=+1

The one on the left, only. The assignment operator (=) must be last, always.

1 Like

Even when this is available on other programming languages like C, C++. Python only allows the i += 1

1 Like

You can also use the syntax i=i+1

This code seems to work fine:

while len(students_in_poetry) < 6:
name = all_students.pop()
students_in_poetry.append(name)

Was I supposed to count index in this exercise?
ps. first time posting - couldn’t figure out how to make indented text in the post… sorry…

No, since we are tracking the length of the students_in_poetry list.