简体   繁体   中英

TypeError: 'int' object does not support item assignment - new to Python

Trying to do some some questions in a book yet I'm stuck with my arrays. I get this error:

count[i] = x
TypeError: 'int' object does not support item assignment

My code:

import pylab
count = 0

for i in range (0,6):
    x = 180
    while x < 300:
        count[i] = x
        x = x + 20
        print count

Basically I need to use a loop to store values which increase until they hit 300 in an array. I'm not sure why I'm getting that error.

I might have worded this poorly. I need to use a loop to make 6 values, from 200, 220, 240... to 300, and store them in an array.

count is an integer. Integers don't have indexes, only lists or tuples (or objects based on them) do.

You want to use a list, and then append values to it:

count = []
for i in range (0,6):
    x = 180
    while x < 300:
        count.append(x)
        x = x + 20
        print count

You have defined count as an int number and as the error says ( 'int' object does not support item assignment ) you need a list instead , :

count = []

and use append() function to append the numbers to your list :

for i in range (0,6):
    x = 180
    while x < 300:
        count.append(x)
        x = x + 20
        print count

You don't need the while loop, you can use range with a start,stop,step:

count = []
for i in xrange (6):
    for x in  xrange(180,300,20):
        count.append(x)
        print count

Or use range with extend:

count = []
for i in xrange(6):
    count.extend(range(180,300,20))

Or simply:

 count range(180,300,20) * 6 `

Use dictionary

count = {}

for i in range (0,6):
    x = 180
    while x < 300:
        count[i] = x
        x = x + 20
        print count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM