raincouver
raincouver

Reputation: 61

Need Help Understanding For loops with Variables in Python

I am going through the book Automate the Boring Stuff with Python, and need help understanding what's really happening with the code.

catNames = []

while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]
print('The cat names are:')
for name in catNames:
    print('  ' + name)

now it makes sense until

for name in catNames:
        print('  ' + name)

I am only used to seeing for loops with range(), and this does not make sense to me. A detailed explanation would be highly appreciated thanks

Upvotes: 0

Views: 86

Answers (1)

FilipA
FilipA

Reputation: 612

I will explain it to you on a simple example:

# You create some list of elements
list = [1, 2, 3, 9, 4]
  
# Using for loop you print out all the elements
for i in list:
    print(i)

It will print to the console:

1
2
3
9
4

And you can also do it by using range but you have to know the length of the array:

# You create some list of elements
list = [1, 2, 3, 9, 4]
  
# get the list length
length = len(list)
  
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
    print(list[i])

Console output will look the same as before

Upvotes: 1

Related Questions