0

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

1
  • Please consider accepting an answer; this tells others that the issue is resolved and helps people find the correct answer more easily. Commented Dec 21, 2020 at 18:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.