You asked:
Please explain to me how the variable, "count", automatically associates itself with each index of the string, "Hello!"
But in your codes, there's no need to use an if statement. And you should add the index or count to near of the item of the string.
Simply the codes should be something like:
greeting = 'Hello!'
count = 0
for item in greeting:
print("item={}, index={}, count={:d}".format(item,greeting.index(item),count))
count += 1
This will print out:
item=H, index=0, count=0
item=e, index=1, count=1
item=l, index=2, count=2
item=l, index=2, count=3
item=o, index=4, count=4
item=!, index=5, count=5
With the above codes you can see that the count is automatically associates with the each index of the string "Hello!". However when you set the count value for example to 1, the 1'st index (Index0) string associates with when the count=1 then multiply it's value until the end of the index with the for loop.
In "Hello!" string there is 6 items. The first item index always starts with 0. However in order to print a more beautiful display, like the 'first item, second item, third item...' you can add a count variable or you can use enumerate function like the below examples:
greeting = 'Hello!'
count = 1
for item in greeting:
print("item={}, index={}, count={:d}".format(item,greeting.index(item),count))
count += 1
greeting = 'Hello!'
for count,item in enumerate(greeting,1):
print("item={}, index={}, count={:d}".format(item,greeting.index(item),count))
The last two codes will give you the same results which are:
item=H, index=0, count=1
item=e, index=1, count=2
item=l, index=2, count=3
item=l, index=2, count=4
item=o, index=4, count=5
item=!, index=5, count=6