在If,Elif,Else循环中比较2个字符串

时间:2017-02-24 01:20:30

标签: python string loops if-statement compare

在我的if / elif / else语句中,我的程序只返回应该是1 B和2 Cs的else。

document = open ("ClassNameGrades.txt","r")

content = document.read().splitlines()
As = 0
Bs = 0
Cs = 0
Ds = 0
Fs = 0

for line in content:
    split = line.split (", ")

    className = split [0]
    facultyName = split [1:1]
    studentName= split [2:2]
    grade = split [3:]

    if str(grade) == ("A"):
        As = As + 1
    elif str(grade) == ("B"):
        Bs = Bs + 1
    elif str(grade) == ("C"):
        Cs = Cs + 1
    elif str(grade) == ("D"):
        Ds = Ds + 1
    else:
        Fs = Fs + 1

print (str(As)+(" students got As."))
print (str(Bs)+(" students got Bs."))
print (str(Cs)+(" students got Cs."))
print (str(Ds)+(" students got Ds."))
print (str(Fs)+(" students got Fs."))

document.close()

结果显示为:

0名学生得到了As。 0名学生得到了Bs。 0名学生获得了Cs。 0名学生得到了Ds。 3名学生获得了Fs。

1 个答案:

答案 0 :(得分:-1)

您正在将列表项与字符串进行比较,这就是您的if条件永远不会评估为True的原因。您应该使用列表索引表示法从列表中获取项目,而不是使用返回列表的列表切片表示法split[2:2]

document = open ("ClassNameGrades.txt","r")

content = document.read().splitlines()
As = 0
Bs = 0
Cs = 0
Ds = 0
Fs = 0

for line in content:

    split = line.split(", ")

    className = split[0]
    facultyName = split[1]
    studentName= split[2]
    grade = split[3]

    if str(grade) == "A":
        As = As + 1
    elif str(grade) == "B":
        Bs = Bs + 1
    elif str(grade) == "C":
        Cs = Cs + 1
    elif str(grade) == "D":
        Ds = Ds + 1
    else:
        Fs = Fs + 1

print(str(As)+(" students got As."))
print(str(Bs)+(" students got Bs."))
print(str(Cs)+(" students got Cs."))
print(str(Ds)+(" students got Ds."))
print(str(Fs)+(" students got Fs."))

document.close()