Reputation: 91
I am following an exercise on the book how to automate the boring stuff and I was wondering what is the purpose of the str(len(catNames) on line 3, will it just add a number after user inputs data e.g. Enter the name of cat 2,3 etc? Thanks in advance!
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] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
Upvotes: 2
Views: 216
Reputation:
See in python you cannot concatenate an integer and a string , so in the above example len(catNames)) returns an integer i.e. length of list catNames. therefore in order to concatenate it with other strings i.e. "Enter the name of cat" you have to make use of str()
function to convert integer to strings
Upvotes: 3
Reputation: 12181
will it just add a number after user inputs data e.g. Enter the name of cat 2,3 etc
Exactly. The str
is to convert this to a string (instead of an integer) because the author wants to do string concatenation, not arithmetic addition.
Upvotes: 2
Reputation: 851
In order to concatenate together strings and numbers, the numbers have to first be converted strings. So the command str(len(catNames) + 1)
simply: 1) Asks what is the length of catNames, and add 1 to this number; 2) Convert that number to a string. Hope this helps.
Upvotes: 2