如何在python上按用户添加项目数组

时间:2018-02-25 11:08:56

标签: python arrays class

我正在学习python,但我不擅长,而且我没有找到关于类结构的足够信息。 İ想要由用户添加项目数组,但我没有。你能帮助我吗?

class Student():
      def __init__(self, no,name,departmant):
        self.no=no
        self.name=name
        self.departmant=departmant

      def add(self):       
       array = []
        n = int(input('number of students to add: '))
        for i in range(n):  
            enter= print("no:",self.no,"name:",self.name,"departmant:",self.departmant)
            array.append(enter)
            print(array)

      def exit(self):
        print("exit...")
        sys.exit(0)

if __name__ == "__main__":

    no=print("enter students no ")
    namee=print("enter students name :")
    depart=print("enter students departman : ")
    studentt=Student(no,namee,depart)
    studentt.add()

2 个答案:

答案 0 :(得分:0)

检查一下:

class Student():
    def __init__(self, no, name, departmant):
        self.no = no
        self.name = name
        self.departmant = departmant
        self.inputMessage = {
            self.no: 'student number to add: ',
            self.name: 'name of student to add: ',
            self.departmant: 'name of departmant to add: '
        }
        self.studentList = []

    def add(self):
        studentDict = {}
        for key, value in self.inputMessage.items():
            userInput = input(value)
            if key == self.no:
                userInput = int(userInput)
            studentDict[key] = userInput

        self.studentList.append(studentDict)

    def show_students(self):
        for student in self.studentList:
            print("{}: {}".format(self.no, student[self.no]))
            print("{}: {}".format(self.name, student[self.name]))
            print("{}: {}".format(self.departmant, student[self.departmant]))

    def exit(self):
        print("exit...")
        sys.exit(0)


if __name__ == "__main__":
    studentClass = Student("no", "name", "departmant")
    studentClass.add()
    print("Result:")
    studentClass.show_students()

当您在课程__init__中添加变量时,请不要在实例化课程时忘记添加变量。

首先实例化您的课程。

然后调用add方法。 add方法将遍历包含条目名称和要显示的输入句子的字典。因此,它将填补所有三个值。您最好将学生添加到列表中,这样您可以多次使用add方法并创建学生存储库。

最后,我添加了show_student,以便您可以看到您将获得的结果。

答案 1 :(得分:0)

首先需要纠正一些错误。我在这里列出他们: IndentationError :在添加功能的第三行。

导入:要使用 sys ,您需要先导入它。

条目:为了获取循环内的条目,您只需要在循环内请求输入。

打印:您正在为输入变量分配print语句,这是没有任何意义的。此外,您正尝试将输入附加到数组,因为 enter 为空,所以再次没用。

退出:您正在使用退出功能仅打印退出... 。你可以在循环之后在add函数内部做到这一点。

我对您的代码中的注释进行了一些温和的更改。我希望它适合你。

祝你好运!#/ p>

如果这有助于你不要忘记upvote。

class Student():
    def add(self):
        array = []
        n = int(input('Enter the number of students to add: '))

        # Your previous input is the number of students you want to add so
        # the inputs of user that you want to take should be inside the loop
        # Only then you will be able to add them in repetitive manner.

        # Then we save the values in array named 'values' here to append in array
        # later. Thus you can save an array of details i.e. values inside an array
        # i.e. array.

        # We have used i+1 to print because in range values start from 0 & not 1.

        for i in range(n):
            no = int(input('Enter the no: '))
            name = input('Enter the name: ')
            department = input('Enter the department: ')

            values = [no, name, department]
            print("\n",i+1,"th entry:","no:",no ,"name:",name, "department:",department)
            array.append(values)
            print(array)

        print('\nExit...')

      # There is no point in calling an exit method as far as I see. But if you 
      # want to print 'exit..' then you can print it inside the add function itself
      # outside the loop after getting your entries.

if __name__ == "__main__":

    # There is no point in printing the sentences asking for no, name & department here
    # You are asking them inside the loop when you actually need them.

    studentt=Student()
    studentt.add()