1
print("""Hi, and welcome to \"GENERATE A CHECK DIGIT \" """)

num1 =input("Enter a 12 digit ISBN number and I will output your check digit:  ")
oddTotal=int(num1[0])+int(num1[2])+int(num1[4])+int(num1[6])+int(num1[8])+int(num1[10])
evenTotal=int(num1[1])+int(num1[3])+int(num1[5])+int(num1[7])+int(num1[9])+int(num1[11])
Total=oddTotal+(evenTotal*3)
checkDigit=10-(Total%10)

print("For the given ISBN: "  + str(num1)+ " The Check digit should be: " + str(checkDigit))
print("Complete ISBN 13 CODE = " +str(num1)+str(checkDigit))

My question: I have added "int" before every single list item but found this to be a bit tedious. I tried putting it at the beginning before the main bracket but it didn't work.

Is there a way of improving this code.

jpp
  • 159,742
  • 34
  • 281
  • 339

2 Answers2

1

You can use sum with map and string slicing:

num1 = input("Enter a 12 digit ISBN number and I will output your check digit:  ")
oddTotal = sum(map(int, num1[::2]))
evenTotal = sum(map(int, num1[1::2]))

The syntax for string slicing is similar to list slicing, i.e. the format is start:end:step.

jpp
  • 159,742
  • 34
  • 281
  • 339
0

You could use a list comprehension to convert all elements of your string num1to integers, and then use list slicing to calculate both sums:

num1 = input("Enter a 12 digit ISBN number and I will output your check digit:  ")
nums = [int(num) for num in num1]
oddTotal = sum(nums[::2])
evenTotal= sum(nums[1::2])
jdamp
  • 1,379
  • 1
  • 15
  • 22
  • I have tried this and it does work. It definitely looks a lot neater. Thank you Could you share some time and explain exactly what is happening in the following lines nums = [int(num) for num in num1] oddTotal = sum(nums[::2]) (What do the :: signify and the "2") evenTotal= sum(nums[1::2]) (Likewise here) – Hamzah Khan Oct 14 '18 at 18:05
  • The second line is a so called list comprehension, which is just a short notation for a `for` loop, see for example [here](https://www.pythonforbeginners.com/basics/list-comprehensions-in-python). For the list slicing syntax(`[::2]` ) good explanations are available at the answers of this question on StackOverflow: https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation. – jdamp Oct 15 '18 at 09:23