cs50 pset6 Credit IndexError: string index out of range
cs50 pset6 Credit IndexError: string index out of range
尝试启动程序时,第 19 行出现“IndexError: string index out of range”错误。是否因为我忘记终止字符串或将其转回 int? python 非常新,所以任何帮助或琐事将不胜感激。
我试过这样做doubleCheck = int(strNumber[i] * 2)
,但没有解决问题。我做错了吗?
这里是完整的代码,以防以后出现错误。
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 字符串索引从 0 开始。对于 N 长度的字符串,有效索引为 0 到 N-1。索引 N 超出范围。
在 for 循环中,您正在访问 strNumber[i]
。在第一次迭代中,i
等于 Numlen
,超出范围。
也许您打算在 Numlen - 1
开始循环?
尝试启动程序时,第 19 行出现“IndexError: string index out of range”错误。是否因为我忘记终止字符串或将其转回 int? python 非常新,所以任何帮助或琐事将不胜感激。
我试过这样做doubleCheck = int(strNumber[i] * 2)
,但没有解决问题。我做错了吗?
这里是完整的代码,以防以后出现错误。
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 字符串索引从 0 开始。对于 N 长度的字符串,有效索引为 0 到 N-1。索引 N 超出范围。
在 for 循环中,您正在访问 strNumber[i]
。在第一次迭代中,i
等于 Numlen
,超出范围。
也许您打算在 Numlen - 1
开始循环?