Coder77
Coder77

Reputation: 2333

Integer list python

I'm having issues with this list, I want to times each number by a certain number, but at the moment each data in the list is a string, and if I turn the list into an integer or turn the string into an integer and make it into an list, I get an error.

def main():
    isbn = input("Enter you're 10 digit ISBN number: ")
    if len(isbn) == 10 and isbn.isdigit():
        list_isbn = list(isbn)
        print (list_isbn)
        print (list_isbn[0] * 2)
    else:
        print("Error, 10 digit number was not inputted and/or letters were inputted.")
        main()


if __name__ == "__main__":
    main()
    input("Press enter to exit: ")

Upvotes: 0

Views: 155

Answers (3)

gprx100
gprx100

Reputation: 360

Change this line

isbn = input("Enter you're 10 digit ISBN number: ")

to

isbn = raw_input("Enter you're 10 digit ISBN number: ")

Upvotes: 0

Jeremy Spencer
Jeremy Spencer

Reputation: 250

@Martijn Pieters answer will not work because input is reading the items as integers already, and in his example he defined the ISBN as a string. --

The problem is that the len builtin function is for sequences (tubles, lists, strings) or mappings (dictionaries) and isbn is an int.

The same holds true for isdigit.

I've posted a working program below:

def main():
    # number to multple by
    digit = 2
    isbn = input("Enter you're 10 digit ISBN number: ")
    # Liste generator that turns each the string from input into a list of ints
    isbn = [int(c) for c in str(isbn)]

    # this if statement checks to make sure the list has 10 items, and they are
    # all int's
    if len(isbn) == 10 and all(isinstance(item, int) for item in isbn):
        # another list generator that multiples the isbn list by digit
        multiplied = [item * digit for item in isbn]
        print multiplied
    else:
        print("Error, 10 digit number was not inputted and/or letters were inputted.")
        main()


if __name__ == "__main__":
    main()
    input("Press enter to exit: ")

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122022

You'd turn each individual character into an integer with:

list_isbn = [int(c) for c in isbn]

Demo:

>>> isbn = '9872037632'
>>> [int(c) for c in isbn]
[9, 8, 7, 2, 0, 3, 7, 6, 3, 2]

Upvotes: 5

Related Questions