-1

I'm a beginner to python. I've written this code but I can't execute the for loop inside the print function to iterate through the list of marks:

class student:
    def __init__(self, name, age, iden, lMark):
        self.name=name
        self.age=age
        self.iden=iden
        self.lMark=lMark
    def printAve(self, obj):
        for i in obj.lMark:
            res+=i
        av=res/len(lMark)
        return av
    def disInfo(self, obj):
        print("the name is: ",obj.name)
        print("the age is: ",obj.age)
        print("the identity is: ",obj.iden)
        print("the marks are: ", for i in lMark:
             print(i))
    def addStudent(self, n, a, i, l):
        ob=student(n,a,i,l)
        ls.append(ob)
        return true
    def searchStudent(self, _val):
        for i in len(ls):
            if ls[i]==_val:
                return i

ls=[]
s=student("Paul", 23,14, list(15,16,17,20,12))
bool added = s.add("Van", 20, 12, list(12,18,14,16))
if added==True:
    print("Student added successfully")
for i in range(ls.__len__())
    s.disInfo(ls[i])

Can someone help me to solve this problem and explain me how to do?

PyPl
  • 3
  • 1
  • 1
    FYI the typical way to get the length of a list named `ls` is `len(ls)` not `ls.__len__()`. For more, see https://stackoverflow.com/questions/2481421/difference-between-len-and-len – jarmod Oct 19 '20 at 17:56
  • the problem is with for i in lMark in the print function – PyPl Oct 19 '20 at 18:01
  • 1
    This code won't even compile. This site isn't a place to get help with such rudimentary syntax problems, and those should be dealt with before you ask about specific logic issues. There are a number of problems here, any one of which could contribute to what you're vaguely saying is wrong. Get a decent IDE that will show you errors right in your source code and then address each problem one by one. If you don't understand how to solve a particular error reported by your IDE, post that here and we'll help you with it. – CryptoFool Oct 19 '20 at 18:01
  • 1
    My comment was just that, a comment. It wasn't intended as an answer to your question. This code has many problems and really needs a rewrite. But before that, I would recommend learning how to use classes first, for example: https://realpython.com/python3-object-oriented-programming/ – jarmod Oct 19 '20 at 18:09

5 Answers5

0

You can't put a bare for loop in the argument list to print, and of course the embedded print doesn't return what it prints. What you can do is

print("the marks are:", ", ".join(lMark))

or perhaps

print("the marks are:", *lMark)

(Also, I believe you mean obj.lMark.)

To reiterate, if you call some code in the argument to print, that code should evaluate to the text you want print to produce; not do printing on its own. For example,

def pi()
    return 3.141592653589793  # not print(3.141592653589793)

def adjective(arg):
    if arg > 100:
        return "big"  # not print("big")
    else:
        return "small"  # not print("small")

print(str(pi()), "is", adjective(pi()))

Notice how each function call returns something, and the caller does something with the returned value.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Neither of these will work in the OPs code because `lMark(s)` is undefined. - and I'm curious...what does `[i for i in lMarks]` do? Isn't that the same as `iMarks`? – CryptoFool Oct 19 '20 at 18:08
  • You're right - I wanted to demonstrate a list comprehension but it's just convoluted. Thanks for the feedback. – tripleee Oct 19 '20 at 18:15
0
from statistics import mean

# classes are named LikeThis
# constants named LIKE_THIS
# other variables should be named like_this
# hungarian notation is not used in Python
class Student:
    # instead of a global variable named ls,
    # I'm using a class variable with a clear name instead
    all_students = []
    def __init__(self, name, age, iden, marks):
        self.name = name
        self.age = age
        self.iden = iden
        self.marks = marks
    def printAve(self):
        # you don't need to pass two arguments when you're only operating on a single object
        # you don't need to reinvent the wheel, see the import statement above
        return mean(self.marks)
    def disInfo(self):
        print("the name is:", self.name)
        print("the age is:", self.age)
        print("the identity is:", self.iden)
        # you can't put a statement inside of an expression
        # I'm guessing you want the marks all on the same line?
        # the *args notation can pass any iterable as multiple arguments
        print("the marks are:", *self.marks)
    # this makes more sense as a classmethod
    # clear variable names are important!
    @classmethod
    def addStudent(cls, name, age, iden, marks):
        # I'm using cls instead of Student here, so you can subclass Student if you so desire
        # (for example HonorStudent), and then HonorStudent.addStudent would create an HonerStudent
        # instead of a plain Student object
        cls.all_students.append(cls(name, age, iden, marks))
        # note the capital letter!
        return True
    # again, this should be a classmethod
    @classmethod
    def searchStudent(cls, student):
        # use standard methods!
        try:
            return cls.all_students.index(student)
        except ValueError:
            return None

# the literal syntax for lists in Python is `[1, 2, 3]`, _not_ `list(1, 2, 3)`.
# it also makes more sense to use Student.addStudent here, because just calling Student() doesn't add it
# to the list (although you could do that in __init__ if you always want to add them to the list)
Student.addStudent("Paul", 23, 14, [15, 16, 17, 20, 12])
# in Python, type annotations are optional, and don't look like they do in C or Java
# you also used `add` instead of `addStudent` here!
added: bool = Student.addStudent("Van", 20, 12, [12,18,14,16])
# don't need == True, that's redundant for a boolean value 
if added:
    print("Student added successfully")

# never call `x.__len__()` instead of `len(x)`
# (almost) never use `for i in range(len(x))` instead of `for item in x`
for student in Student.all_students:
    student.disInfo()
Jasmijn
  • 9,370
  • 2
  • 29
  • 43
0

First I answer your initial question, you can print a list in different ways, here are some of them. You can iterate through it with a for loop and print every element on a different line:

for elem in self.lMark:
    print(elem)

You can also append all values to a string and separate them by a character or something. (Note: There will be a trailing space at the end.)

myString = ""
for elem in self.lMark:
    myString = myString + str(elem) + " "
print(myString)

Better is this by doing it with strings-join method and a short version of the container iteration:

", ".join([str(i) for i in self.lMark])

There were some more issues in the code example. Here is a running version of the script:

class Student:
    def __init__(self, name, age, iden, lMark):
        self.name=name
        self.age=age
        self.iden=iden
        self.lMark=lMark

    def printAve(self, obj):
        for i in obj.lMark:
            res+=i
        av=res/len(self.lMark)
        return av

    def disInfo(self):
        print("the name is: ",self.name)
        print("the age is: ",self.age)
        print("the identity is: ",self.iden)
        print("the marks are: ", ", ".join([str(i) for i in self.lMark]))


class StudentList:
    def __init__(self):
        self.__list_of_students = []

    def add(self, s):
        self.__list_of_students.append(s)
        return True
    
    def get(self):
        return self.__list_of_students

    def search(self, name):
        for s in self.__list_of_students:
            if s.name == name:
                return s
        
        return None

ls = StudentList()
s=Student("Paul", 23,14, [15,16,17,20,12])
ls.add(s)
added = ls.add(Student("Van", 20, 12, [12,18,14,16]))

if added:
    print("Student added successfully")

search_name1 = "Paula"
search_name2 = "Van"

if ls.search(search_name1):
    print(search_name1, "is part of the list!")
else:
    print("There is no", search_name1)


if ls.search(search_name2):
    print(search_name2, "is part of the list!")
else:
    print("There is no", search_name2)

for student in ls.get():
    student.disInfo()
    print("-"*10)

I would suggest to separate the list of students and the students to two different classes as shown in the code above.

0

You can unpack your list with the * operator:

print("the marks are: ", *lMark)
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
-2

Try setting this as a function. i.e

def quantity():
    for i in lMark:
        print(i)

Then,

def disInfo(self, obj):
    print("the name is: ",obj.name)
    print("the age is: ",obj.age)
    print("the identity is: ",obj.iden)
    print("the marks are: ", + quantity)