-2

I am in need of some help. I don't know why the type error, list indices must be integers, not str, comes up. I'm trying to take the first character of isbn and multiply it by 10, and the second by 9, and so on. And after that has finished I need to find if the total is a multiple of 11.

isbn = ['0439202116']
count = 10
x = 0
for x in isbn:
    total = isbn[x] * count
    count -= 1
    x += 1
    if (total % 11 == 0):
        print(True)
    else:
        print(False)
Tosh
  • 25
  • 7
  • list[0], list[1], list[2]... here 1,2,3 represent indices – Ayush Nov 23 '15 at 19:07
  • You're not iterating over the string in `isbn` list, but the list itself. `x` in first iteration will be `'0439202116'`. – Rohit Jain Nov 23 '15 at 19:07
  • Rohit Jain, How can I iterate over the string? – Tosh Nov 23 '15 at 19:09
  • When using `for x in iterableObject`in python, you don't have to do `x += 1`. Also, instead of using 4 lines to print `True` or `False`, you can just do `print(condition)` : `print(tot % 11 == 0)` – Loïc G. Nov 23 '15 at 19:39

3 Answers3

0

start with isbn as a string:

isbn = '0439202116'
count = 10
tot = 0
for x in isbn:
    tot += int(x) * count
    count -= 1

if tot % 11 == 0:
    print 'True'
else:
    print 'False'

i assume you only want to test for multiples of 11 on the final total

gkusner
  • 1,244
  • 1
  • 11
  • 14
0

You're trying to iterate over the list of the string of the combined digits - it'll only give you the item at index 0. The index of any given item in a string,list,etc refers to it's place in the order of the string, starting at 0. The indices, then, refer to multiple indexes. Change your initial string into a tuple containing all the digits of the ISBN, and it works fine.

isbn = (0,4,3,9,2,0,2,1,1,6)
count = 10
x = 0
for x in isbn:
    total = isbn[x] * count
    count -= 1
    x += 1
    if (total % 11 == 0):
        print(True)
    else:
        print(False)

This gives me an output of:

True
False
False
False
False
True
False
False
False
False
n1c9
  • 2,662
  • 3
  • 32
  • 52
  • Im trying to find, (10*0 + 9*4 + 8*3 + 7*9 + 6*2 + 5*0 + 4* 2 + 3*1 + 2*1 + 1*6) then I want to see if the total from that is a multiple of 11. I figured I need to do what you are doing in the first line, but can you help with the total. There should only be one outcome. – Tosh Nov 23 '15 at 19:34
  • Also I had to change isbn to isbn = ['0', '4', '3', '9', '2', '0', '2', '1', '1', '6'] , is there a way to do it this way? with strings instead of int, I cant seem to find a way to change it to int – Tosh Nov 23 '15 at 19:47
0

this is a litter more general solution in case you wish more than one item on your isbn list.

isbn = ['0439202116', '0439202115']
for str in isbn:
    count = len(str)
    total = 0
    for ch in str:
        total += count * ord(ch)
        count -= 1
    print ("{0} => {1}" .format(str, total % 11 == 0))

Output:

0439202116 => True
0439202115 => False
Luis Daniel
  • 687
  • 7
  • 18