1

When trying to launch the program, I get the "IndexError: string index out of range" error on line 19. Is it because I forgot to terminate the string or turn it back to int? Very new to python, so any help or trivia would be appreciated.

I tried doing something like thisdoubleCheck = int(strNumber[i] * 2) , but it did not solve the problem. Am I doing it wrong?

Here is the full code just in case of later errors.

from cs50 import get_int 
import sys

ccNumber = get_int("Number: ")
strNumber = str(ccNumber)
Numlen = len(str(ccNumber))

if Numlen != 13 and Numlen != 15 and Numlen != 16:
    sys.exit()

firstSum = 0
secondSum = 0
doubleCheck = 0

for i in range(Numlen, -1, -1):
    if i % 2 == 0:
        secondSum = secondSum + strNumber[i]
    if i % 2 == 1:
        doubleCheck = strNumber[i] * 2
        if doubleCheck >= 10:
            firstSum = firstSum + (doubleCheck % 10)
            firstSum = firstSum + (doubleCheck / 10)
        else:
            firstSum += doubleCheck;

totalChecksum = firstSum + secondSum

if totalChecksum % 10 == 0:
    if strNumber[0] == 3 and Numlen == 15:
        if strNumber[1] == 4 or strNumber[1] == 7:
            print("AMEX", end="");
    elif strNumber[0] == 4:
        if Numlen == 13 or Numlen == 16:
            print("VISA", end="")
    elif strNumber[0] == 5 and Numlen == 16:
        if strNumber[1] == 1 or strNumber[1] == 2 or strNumber[1] == 4 or strNumber[1] == 5:
            print("MASTERCARD", end="")
else:
    print("INVALID", end="")

1 Answers1

1

Python string indexing starts at 0. For an N-length string, valid indexes are 0 through N-1. Index N is out of range.

In the for loop, you're accessing strNumber[i]. On the first iteration, i is equal to Numlen, which is out of range.

Perhaps you intended to start the loop at Numlen - 1?

John Gordon
  • 29,573
  • 7
  • 33
  • 58