Home > front end >  I have problem with last for loop. It shows me just last student in array, but it should be all 5
I have problem with last for loop. It shows me just last student in array, but it should be all 5

Time:05-12

I have a problem with for loop. how can I solve it?

Here 3 arrays which I need to put in for loop and print by class:

name = ["Scott", "Liz", "Sarah", "Mark", "Dan"]
address = ["21, old kent road", "13,Trafalgar Square", "45,KingsCross Road", "33,Russel square",
           "56,Lewisham Road"]
telephone = ["02075642222", "02078642123", "02084641111", "02085553234", "02076662123"]
students = []

here I loop and launch my class that print all students:

for i in range(len(name),len(address),len(telephone)):
    stud1 = Studentdetails(name[i], address[i], telephone[I])

I have problem with last for loop. It shows me just last student in array, but it should be all 5.

CodePudding user response:

All your lists are length 5 (and I assume they will always be the same length), so there's no need to factor in all their different lengths. You just need the length of one of them in order to loop. The way you have it currently, you're doing range(5, 5, 5), which is empty, because of the behavior of range given those arguments. Like I said in my comment, the first number is the starting number, the second number is the ending number, and the third number is the "step". For more info see: https://docs.python.org/3/library/functions.html#func-range

So, your code should work fine if you do:

for i in range(len(name)):
    stud1 = Studentdetails(name[i], address[i], telephone[i])

There are more ways to make this more "Pythonic" but you can feel free to ignore everything below if it's too confusing:

You can use the zip function to iterate through all 3 lists at once, with each item in the zip being a tuple of the 3 list items for that index. So, this would work just as well:

for n, a, t in zip(name, address, telephone):
    stud1 = Studentdetails(n, a, t)

You could also use the asterisk operator to automatically expand the tuple into a list of arguments to pass to Studentdetails:

for s in zip(name, address, telephone):
    stud1 = Studentdetails(*s)

CodePudding user response:

Generally avoid using range(len) you almost always don't need it. Python for works like for each.

If your studentdetails takes the three arguments you can use zip to loop over multiple items and unpack it with *:

for student in zip(name, address, telephone):
    students.append(studentdetails(*student))

This is equivalent to:

for studentname, studentaddress, studenttel in zip(name, address, telephone):
    students.append(studentdetails(studentname, studentaddress, studenttel))

If you are going to be doing this for a larger set of data the fastest way to fill the students list with the results of studentdetails() would be to add a short generator which unpacks the zip and yields the studentdetails() for each set of details:

def createstudents(iter):
    for item in iter:
        yield studentdetails(*item)

students = list(createstudents(zip(name, address, telephone)))

This then reads like the sentence: "students is the list of createstudents for each group of name, address, telephone)" and createstudents is "for each item in the iterator: yield me the studentdetails object"

For great insights in the pythonic way of doing this sort of thing check out the first 10 minutes of: https://www.youtube.com/watch?v=OSGv2VnC0go

CodePudding user response:

I suspect that Studentdetails is a class so I'll emulate it here and show how a list of students could be constructed:

class Studentdetails:
    def __init__(self, name, address, telephone):
        self.name = name
        self.address = address
        self.telephone = telephone
    def __repr__(self):
        return f'Name={self.name}, Address={self.address}, Telephone={self.telephone}'

name = ["Scott", "Liz", "Sarah", "Mark", "Dan"]
address = ["21, old kent road", "13,Trafalgar Square", "45,KingsCross Road", "33,Russel square",
           "56,Lewisham Road"]
telephone = ["02075642222", "02078642123", "02084641111", "02085553234", "02076662123"]
students = []

assert len(name) == len(address) and len(address) == len(telephone)

for name_, address_, telephone_ in zip(name, address, telephone):
    students.append(Studentdetails(name_, address_, telephone_))

for student in students:
    print(student)

Output:

Name=Scott, Address=21, old kent road, Telephone=02075642222
Name=Liz, Address=13,Trafalgar Square, Telephone=02078642123
Name=Sarah, Address=45,KingsCross Road, Telephone=02084641111
Name=Mark, Address=33,Russel square, Telephone=02085553234
Name=Dan, Address=56,Lewisham Road, Telephone=02076662123

CodePudding user response:

class Studentdetails:
    def __init__(self, name, address, telephone, address2="London"):
        self.name = name
        self.address = address
        self.telephone = telephone
        self.city = address2

    def __repr__(self):
        return f'Name={self.name}, Address={self.address}, City={self.city}, Telephone={self.telephone}'


class Totalmarks():
    def __init__(self, total=0.0, average=0.0):
        self.totmarks = total
        self.average = average

    def total(self, total):
        self.markslist = total
        for i in range(5):
            self.totmarks = self.totmarks   self.markslist[i]
        return self.totmarks

    def Aver(self):
        self.average = self.totmarks / 5
        return self.average


class Teachercomments():
    def comments(self, average):
        self.average = average
        if self.average <= 30:
            print("Teacher Comments: ", "\n", "Needs to work hard and attend extra sessions to progress.")
        elif self.average >= 31 and self.average <= 50:
            print("Teacher Comments: ", "\n", "Needs to improve the quality of work produced to make a progression")
        elif self.average >= 51 and self.average <= 70:
            print("Teacher Comments: ", "\n",
                  "Making good progress but need to focus on certain topics to achieve high marks")
        elif self.average >= 71 and self.average <= 80:
            print("Teacher Comments: ", "\n", "Needs to be carefully")
        else:
            print("Teacher Comments: ", "\n", "Well done for making an excellent progress.")


def report():
    s = "*" * 65
    studtotal = Totalmarks()
    print(s, "\n", " " * 20, "Student Report", "\n", s)
    marks = []
    for i in range(5):
        smarks = int(input("please enter your mark"))
        marks.append(smarks)
    print(marks)
    sumtot = studtotal.total(marks)
    av = studtotal.Aver()
    print("Total marks:", sumtot)
    print("Average:", av)
    tcom = Teachercomments()
    tcom.comments(av)
report()



name = ["Scott", "Liz", "Sarah", "Mark", "Dan"]
address = ["21, old kent road", "13,Trafalgar Square", "45,KingsCross Road", "33,Russel square",
           "56,Lewisham Road"]
telephone = ["02075642222", "02078642123", "02084641111", "02085553234", "02076662123"]
students = []

assert len(name) == len(address) and len(address) == len(telephone)

for name_, address_, telephone_ in zip(name, address, telephone):
    students.append(Studentdetails(name_, address_, telephone_))

for student in students:
    print(student)

Output

***************************************************************** 
                      Student Report 
 *****************************************************************
please enter your mark1
please enter your mark2
please enter your mark3
please enter your mark4
please enter your mark45
[1, 2, 3, 4, 45]
Total marks: 55.0
Average: 11.0
Teacher Comments:  
 Needs to work hard and attend extra sessions to progress.
Name=Scott, Address=21, old kent road, City=London, Telephone=02075642222
Name=Liz, Address=13,Trafalgar Square, City=London, Telephone=02078642123
Name=Sarah, Address=45,KingsCross Road, City=London, Telephone=02084641111
Name=Mark, Address=33,Russel square, City=London, Telephone=02085553234
Name=Dan, Address=56,Lewisham Road, City=London, Telephone=02076662123
  • Related