Range in loop

the first is:

i = 0
for i in len(names): (line #14)
  name = names[i]
  insurance_cost = actual_insurance_costs[i]
  print("The insurance cost for"+" "+ names[i]+" "+"is"+" "+str(insurance_cost)+" "+"dollars")

result:
raceback (most recent call last):
File “script.py”, line 14, in
for i in len(names):
TypeError: ‘int’ object is not iterable

when I revised into:

or i in range(len(names)):
  name = names[i]
  insurance_cost = actual_insurance_costs[i]
  print("The insurance cost for"+" "+ names[i]+" "+"is"+" "+str(insurance_cost)+" "+"dollars")

The result is done

So what makes the difference?

Thanks!

Heya!

In order to loop over a given range, python needs to be provided with an “Iterator”, which is an object that contains a countable number of values and can be iterated over.

In the first example you provide an int which cannot be iterated over as is shown in the error message.
In the second example you use range() which is an object that contains a sequence of numbers which can be iterated over.

Hope this helps and happy coding!

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.