简体   繁体   English

cs50 pset6 Credit IndexError:字符串索引超出范围

[英]cs50 pset6 Credit IndexError: string index out of range

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?尝试启动程序时,我在第 19 行收到“IndexError: string index out of range”错误。是否因为我忘记终止字符串或将其转回 int? Very new to python, so any help or trivia would be appreciated.对python非常陌生,因此将不胜感激任何帮助或琐事。

I tried doing something like this doubleCheck = int(strNumber[i] * 2) , but it did not solve the problem.我尝试做这样的事情doubleCheck = int(strNumber[i] * 2) ,但它没有解决问题。 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="")

Python string indexing starts at 0. For an N-length string, valid indexes are 0 through N-1. Python 字符串索引从 0 开始。对于长度为 N 的字符串,有效索引为 0 到 N-1。 Index N is out of range.索引 N 超出范围。

In the for loop, you're accessing strNumber[i] .在 for 循环中,您正在访问strNumber[i] On the first iteration, i is equal to Numlen , which is out of range.在第一次迭代中, i等于Numlen ,超出范围。

Perhaps you intended to start the loop at Numlen - 1 ?也许您打算从Numlen - 1开始循环?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM