for循环后将不执行打印语句

时间:2019-08-09 23:56:36

标签: python

"""
ID: kunalgu1
LANG: PYTHON3
TASK: ride
"""
fin = open ('ride.in', 'r')

fout = open ('ride.out', 'w')
lines = fin.readlines()

cometString = lines[0]
cometValue = 1

groupString = lines[1]
groupValue = 1

def orderS (val):
    arrL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 
    arrN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
    indexVal = arrL.index(val.lower())
    return arrN[indexVal]

for x in cometString:
    print(orderS(x))
    cometValue *= orderS(x)
    print(cometValue)

这是主要错误:不会打印

cometValue = cometValue % 47
print(cometValue)

fout.close()

1 个答案:

答案 0 :(得分:1)

循环出错,因为readlines()返回的行包含换行符终止符。当它为该字符调用orderS()时,arrL.index()会失败,因为arrL中没有换行符。

您可以使用rstrip()方法删除换行符:

cometString = lines[0].rstrip()

当找不到字符时,您还可以让orderS()返回默认值:

def orderS (val):
    arrL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 
    arrN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
    try:
        indexVal = arrL.index(val.lower())
        return arrN[indexVal]
    except ValueError:
        return 27