for-loops(如果需要,我怎么能让它忽略一些部分)

时间:2017-11-06 19:50:27

标签: python python-3.x python-requests

def reporta():
    with open("userinfo.txt","r") as f:
        text = [line.strip() for line in f]
        ulist = [x.split(",") for x in text]
    for n in range(len(ulist)):
        uname = input("Which username do you want to see?\n")
        if uname == ulist[n][0]:
            print("The username is",ulist[n][0],"\nThe user's password is",ulist[n][1],"\nThe user's name is",
                  ulist[n][2],"\nThe user's age is",ulist[n][3],"\nThe user's year group is",ulist[n][4])
            for i in range (5,11):
                if i == 5:
                    if ulist[n][i] == "-1":
                        print("Maths easy has not been taken by",ulist[n][0])
                    else:
                        print(ulist[n][0],"got",ulist[n][i])
                elif i == 6:
                    if ulist[n][i] == "-1":
                        print("Maths medium has not been taken by",ulist[n][0])
                    else:
                        print(ulist[n][0],"got",ulist[n][i])
                elif i == 7:
                    if ulist[n][i] == "-1":
                        print("Maths hard has not been taken by",ulist[n][0])
                    else:
                        print(ulist[n][0],"got",ulist[n][i])
                elif i == 8:
                    if ulist[n][i] == "-1":
                        print("History easy has not been taken by",ulist[n][0])
                    else:
                        print(ulist[n][0],"got",ulist[n][i])
                elif i == 9:
                    if ulist[n][i] == "-1":
                        print("History medium has not been taken by",ulist[n][0])
                    else:
                        print(ulist[n][0],"got",ulist[n][i])
                else:
                    if ulist[n][i] == "-1":
                        print("History hard has not been taken by",ulist[n][0])
                    else:
                        print(ulist[n][0],"got",ulist[n][i])
            break

在这段代码中,我试图根据输入的用户名从文件中打印东西,但是,如果我尝试在列表的第二行或第三行输入用户名,我必须输入用户名在识别它之前两到三次。我不包括/做错了什么?

示例:

file contains:
aad15,arbiter,aadam,15,11,-1,-1,-1,-1,-1,-1
jam11,jammy,james,11,15,-1,-1,-1,-1,-1,-1
ton15,tonehh,tony,15,11,-1,-1,-1,-1,-1,-1
mas15,radicallx,mash,15,11,-1,-1,-1,-1,-1,-1

如果我输入aad15作为用户名,它会按预期运行程序。如果我输入jam11,我必须输入两次才能完成它应该做的事情。如果我把ton15放入其中我必须输入它三次才能完成它应该做的事情等等。

1 个答案:

答案 0 :(得分:1)

简单明了:循环中有输入行,因此它在循环的每次传递中都要求用户输入。将uname = input("Which username do you want to see?\n")移至for n in range(len(ulist)):

上方的行

但是,正如@pvg所述,请查看using examples when asking questions上的指南。