User-given input produces TypeError: list indices must be integers or slices, not str

Viewed 81

I'm new to Python, it appear my data when I enter student name, but I can't modify my data. The following error message appeared:

TypeError: list indices must be integers or slices, not str.
if userChoice == '1':
    allrec = []
    with open("student.txt") as fh:
        for line in fh:
            rec = line.strip().split(":")
            allrec.append(rec)
        skey = input("Please enter Student Name: ")
        flg = -1
        for cnt in range(len(allrec)):
            if skey in allrec[cnt][1]:
                flg = cnt
                break
        if flg != -1:
                print("1 -Student ID   :" + allrec[flg][0])
                print("2 -Name     :" + allrec[flg][1])
                print("3 -S1 Marks :" + allrec[flg][2])
                print("4 -S2 Marks :" + allrec[flg][3])
                print("5 -S3 Marks :" + allrec[flg][4])
                ans = input("Enter the number to modify :")

                allrec[cnt][ans] = input("Enter a new value: ")
                with open("suppliers.txt", "w") as fh:
                    for cnt in range(len(allrec)):
                        rec = ":".join(allrec[cnt]) + "\n"
1 Answers

input() returns a string containing whatever the user entered; you need to explicitly transform it into an integer:

ans = input("Enter the number to modify :")

should be

ans = int(input("Enter the number to modify :"))
Related