Domanda

In this program, i want marks of 3 subjects per each student, for 4 students. But when i run this one, i get an error like this:

Traceback (most recent call last):
 File "E:\Python\Lab\Lab6_3.py", line 12, in <module>
    for marks in marks[student]:
TypeError: 'float' object has no attribute '__getitem__'

I can't identify what's wrong with, using the len() function to find the number of elements in a list. Here's the code:

while True:
    try:
        marks=[]
        print "Enter marks of the 3 subjects of each student : "
        for student in range(4):
            marks.append(raw_input())
            marks[student]=map(float,marks[student].split(" "))
            if len(marks[student])!=3:
                print "Please enter marks of 3 subjects per each student"
        for student in range(4):
            total=0
            for marks in marks[student]:
                if marks<0:
                    print "You have entered a minus value"
                total+=marks
            print "Total of student %d = %f" %((student+1),total)
        break
    #except TypeError:
    #    print "You have entered an invalid input1"
    except ValueError:
        print "You have entered an invalid input2"
    except NameError:
        print "You have entered an invalid input3"
    except SyntaxError:
        print "You have entered an invalid input4"
    else:
        print "DONE !\n"

Here, I have skipped the exception "TypeError" to identify the fault. Can anybody tell what's wrong with this code?

È stato utile?

Soluzione

marks is only an iterable the first time through the outer loop. Since marks is also the name you use in the inner loop, the iterable no longer exists in the outer loop.

TL;DR: for loops don't create a new scope in Python.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top