I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.
Just create a string out of it.
myinteger = 212345 number_string = str(myinteger)
That's enough. Now you can iterate over it:
for ch in number_string: print ch # will print each digit in order
Or you can slice it:
print number_string[:2] # first two digits print number_string[-3:] # last three digits print number_string # forth digit
Or better, don't convert the user's input to an integer (the user types a string)
isbn = raw_input() for pos, ch in enumerate(reversed(isbn)): print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)
For more information read a tutorial.
while number: digit = number % 10 # do whatever with digit # remove last digit from number (as integer) number //= 10
On each iteration of the loop, it removes the last digit from number, assigning it to
It's in reverse, starts from the last digit, finishes with the first