Studenten = [] while True: print("(i) immatrikulieren") print("(e) exmatrikulieren") print("(a) anzeigen aller Studenten") print("(s) zum schreiben in textdatei") print("(x) beenden") eingabe = input() if (eingabe == 'i'): name = input("Namen eingeben ") vorname = input("Vornamen eingeben ") matnr = int(input("Matrikelnummer eingeben ")) s = student.Student(vorname, name, matnr) Studenten.append(s) elif (eingabe == 'e'): exnr = int(input("Matrikelnummer eingeben ")) for i in range(len(Studenten)): if exnr == Studenten[i].matnr: Studenten.pop(i) elif (eingabe == 'a'): for i in range(len(Studenten)): print(Studenten[i].name) print(Studenten[i].vorname) print(Studenten[i].matnr) elif (eingabe == 'x'): break elif (eingabe == 's'):
import pickle import student f = open("stud.dat", "wb") s = student.Student(1025, "Snk", 90) pickle.dump(s, f) # syntax pickle,dump(content,file opened)
import student stu1 = student.Student('Bob', 20) stu1.print_name() # print stu1.__name print stu1.get_name()
导入的模块是用于定义的--定义类、变量、函数 首次导入会运行模块中的代码 *如果有导入时不希望执行的代码,可以放在if __name__ == '__main__'条件语句下 *再次导入不会运行。除非使用reload(模块名)函数 导入的几种情况 *导入文件 import student #python文件不用写.py 使用文件中的类、方法 student.Student() student.Student().成员变量和成员方法 student.Student.类变量和类方法 student.sum() *导入类、导入方法 即:从文件中导入类、方法 from student import Student from student import sum from student import Student, sum 使用类、方法 Student() Student().成员变量和成员方法
def createStudent(m, i, pro, ex): return student.Student(m, i, pro, ex)
def addNewStudent(): def setStudentNo(): studentNo_ = input( "3 reqemden ibaret telebe nomresini daxil edin: ").strip() if studentNo_.isdigit() and len(studentNo_) == 3: for s in student.userList: if s.studentNo == studentNo_: print("Bu koda sahib telebe artiq sistemde var!") return return studentNo_ else: print("Telebe nomresi dogru daxil edilmeyib!") studentNo = setStudentNo() def setName(): name_ = input("Adi daxil edin: ").strip() if len(name_) != 0: return name_ else: print("Ad bosh ola bilmez! Daxil edin.") name = "" if bool(studentNo): name = setName() def setSurname(): surname_ = input("Soyadi daxil edin: ").strip() if len(surname_) != 0: return surname_ else: print("Soyad bosh ola bilmez! Daxil edin.") surname = "" if bool(name): surname = setSurname() def setEmail(): email_ = input("Emaili daxil edin: ").strip() if email_.find("@") != -1 and len(email_) != 0: return email_ else: print( "Email melumatlari dogru daxil edilmeyib! Tekarar daxil edin.") email = "" if bool(surname): email = setEmail() def setPhone(): phone_ = input( "Telefon nomresini daxil edin (+994_________): ").strip() if phone_.startswith("+994") and len( phone_) == 13 and len(phone_) != 0: return phone_ else: print("Telefon nomresi dogru daxil edilmeyib! Tekrar daxil edin.") phone = "" if bool(email): phone = setPhone() if bool(studentNo) and bool(name) and bool(surname) and bool( email) and bool(phone): obj = student.Student(studentNo, name, surname, email, phone) student.userList.append(obj)
def phantom(): return student.Student(data, identifier=identifier, headers = course.students[0].headers)
def process_student_file(): #Declare variables #Declare file_found variable as True file_found = True #Declare good_data variable as True good_data = True #Exception Block #Try opening your input file try: #Open input file student_file = open(INPUT, 'r') #Except if the file cannot be found, except FileNotFoundError: #Print error print("Could not find", INPUT, "in the current directory.") #Re-set variable file_found = False #If everything looks good, continue with logic if file_found: #Create a blank dictionary student_dict = {} #Read the first name line student_data = student_file.readline().rstrip('\n') #Initialize n n=0 #Create student instances while (student_data != ""): #Split the string student_list = student_data.split(':') #Set uteid string equal to a variable uteid = student_list[0] #Set first name string to a variable first_name = student_list[1] #Set last name string to a variable last_name = student_list[2] #Create an index variable index = int(3) #Create a blank class list class_list = [] #While the length of the student list is greater than the index, while (len(student_list) > index): #Set a variable equal to each number class_1 = int(student_list[index]) #Append the numbers into a list class_list.append(class_1) #Change the index index = index + 1 #Create a new student object student_object = student.Student(uteid, first_name, last_name, class_list) #Append to the student dictionary student_dict.update({uteid: student_object}) #Read the first name line student_data = student_file.readline().rstrip('\n') #Return the student dictionary return student_dict
# 模块 module # PYTHONPATH print(".................方法一...................") import student print(student.my_name) print(student.list_name[2]) student.who_am_i("dennis") kate = student.Student("kate.li",15,"female") kate.who_am_i() print("..................分割线...............") import sys print(sys.path) print("..............................") for line in sys.path: print(line) print(".................方法二...................") from student import Student,my_name,who_am_i kate = Student("kate.li",15,"female") kate.who_am_i() print(my_name) print(who_am_i("robin")) print(".................测试一...................") my_name = "dell" from student import my_name print(my_name) print(".................测试二...................") my_name = "dell" from student import my_name my_name = "luis" print(my_name)
import pickle, student f = open("student.dat", "wb") s = student.Student(123, "John", 90) pickle.dump(s, f) f.close()
def main(): print('Building database ...') controller.createDB() menu1 = menu.Menu() id = "" pw = "" userRecord = None authorized = False while not authorized: os.system('cls' if os.name == 'nt' else 'clear') print("School Records Application") #get id and password from user id = menu1.getID() if id == "": print("Username cannot be blank.") return pw = menu1.getPassword() if pw == "": print("Password cannot be blank") return #authenticate userRecord = controller.authenticate(id, pw) if userRecord != None: authorized = True else: print("Invalid login - Access denied") input("Press enter to continue ...") #end while id = userRecord[0] privilege = userRecord[5] choice = "" if privilege == 'student': data = controller.getStudentData(id) st = student.Student(data[0], data[1], data[2], data[3], data[4], data[5], data[6]) os.system('cls' if os.name == 'nt' else 'clear') menu1.welcome(st.firstName) while choice != "0": choice = menu1.studentMain(st.id) if choice == '1': menu1.viewStudentRecord(st.id) elif choice == '2': menu1.viewAllCourses() elif choice == '3': course1 = menu1.enrollMenu() #returns Course object numStudents = controller.numStudentsInCourse(course1.id) if numStudents[0] >= course1.studentLimit: print("This class is full. Enrollment Aborted.") return #check if already enrolled enrolled = controller.isEnrolled(st.id, course1.id) if enrolled: print(f"You are already enrolled in {course1.name}.") else: controller.enroll(st.id, course1.id) print("You are now enrolled.") elif choice == '0': print("Goodbye!") return else: print("Invalid entry.\n") #pause and clear console input("Press Enter to continue ...") os.system('cls' if os.name == 'nt' else 'clear') #End while elif privilege == 'faculty': data = controller.getFacultyData(id) fac = faculty.Faculty(data[0], data[1], data[2], data[3], data[4], data[5]) os.system('cls' if os.name == 'nt' else 'clear') menu1.welcome(fac.firstName) while choice != '0': choice = menu1.facultyMain(fac.id) if choice == '1': menu1.facViewStudentRecord() elif choice == '2': menu1.viewCourseRecords(fac.id) elif choice == '3': menu1.gradeStudent(fac.id) elif choice == '0': print("Goodbye!") else: print("Invalid entry.\n") #pause and clear console input("Press Enter to continue ...") os.system('cls' if os.name == 'nt' else 'clear')
# zc-cris import student person = student.Person('rose', 22) person.eat() # rose is eatting~~~ student = student.Student('curry', 25, 190) student.descripe() # 我叫curry, 今年25岁了,身高190, 我的书包的详细信息是:这是个adidas 的书包,价格:100
print("") print("1. Add a student") print("2. Remove a student") print("3. Display grades for a student") print("4. Display grades for all students") print("5. Exit") choice = int(input("Please make a selection from the menu above: ")) if choice == 1: sFirst = input("What is students first name: ") sLast = input("What is students last name: ") courseId = input("What is the course id: ") courseCredit = input("How many credit hours is it worth: ") courseGrade = input("What was the grade achieved: ") studentInfo = student.Student(sFirst, sLast) course = collegecourse.CollegeCourse(courseId, courseCredit, courseGrade) studentInfo.addcourse(course) studentdata.addstudent(studentInfo) elif choice == 2: try: sId = int( input( "What is the student id of the student you wish to remove: " )) studentdata.removestudent(sId) except KeyError: print("ID not found.") elif choice == 3: try:
# # def __init__(self, message): # super().__init__() # self.message = message # # def get_exception_message(self): # return self.message if __name__ == '__main__': group = group.Group() stud1 = student.Student('Ivanenko', 'Ivan', 20, 95) stud2 = student.Student('Prokopenko', 'Milana', 19, 90) group.add_to_group(stud1) group.add_to_group(stud2) # print(group) # print('*' * 80) # group.remove_from_group(stud2) # print(group) # print('Id student is: ', group.search(stud2)) for stud in group: print(stud)
def main(): survey = open("survey.txt", "r") # opens the file with list of students who filled out survey lines = survey.readlines() name = [] # list that stores the first and last names of students that filled out the survey ID = [] # list that stores the career IDs of students that filled out survey email = [] # list that stores the email of students that filled out survey major = [] # list that stores the major of students that filled out survey year = [] # list that stores the classification year of students that filled out survey section = [] # list that stores requested class section of students that filled out survey students = [None] * len(lines) # list of students (objects) index = 0 # first index in the students list for line in lines: name.append(line[:18].strip()) ID.append(line.split()[2]) # gets the Purdue username of the student email.append(line.split()[3]) # gets the Purdue email of the student major.append(line[80:120].strip()) # gets the major of the student year.append(line[120:140].strip()) # gets the class year of the student section.append(line[140:].strip()) # gets the section requested from the student students[index] = student.Student(name[index], ID[index], email[index], major[index], year[index], section[index]) # stores the retrieved attributes in student object index = index + 1 # changes index survey.close() # closes the survey file ########################################################################### # store the attriubutes of students in the data base into different lists # ########################################################################### database = open("studentlist.txt", "r") # opens the data base with correct student information lines = database.readlines() studentDatabase = [] # a list of students containing correct attributes index = 0 for line in lines: # stores students in database in list studentDatabase.append(line.split()) # joins the first and last name studentDatabase[index][0] = ' '.join(studentDatabase[index][0 : 2]) del(studentDatabase[index][1]) # corrects the issue with the length of major if(len(studentDatabase[index]) == 8): studentDatabase[index][3] = ' '.join(studentDatabase[index][3 : 7]) del(studentDatabase[index][4 : 7]) if(len(studentDatabase[index]) == 7): studentDatabase[index][3] = ' '.join(studentDatabase[index][3 : 6]) del(studentDatabase[index][4 : 6]) if(len(studentDatabase[index]) == 6): studentDatabase[index][3] = ' '.join(studentDatabase[index][3 : 5]) del(studentDatabase[index][4 : 5]) index = index + 1 # changes the index database.close() # closes the data base file delete = [] # the indexes of student objects that need to be deleted ########################## # Corrections for Survey # ########################## # 1. Remove duplicates (students that filled out survey twice) for outerCount in range(len(students)): for innerCount in range(outerCount + 1, len(students)): if(students[outerCount].get_name() == students[innerCount].get_name()): # finds the duplicate student delete.append(innerCount) # deletes the duplicates in the list for index in delete: students[index] = None # creates none for the object students = list(filter(None, students)) # removes the empty students from the list # Find the index of where each student appears in the database for index in range(len(studentDatabase)): for lcv in range(len(students)): count = studentDatabase[index].count(students[lcv].get_name()) if(count > 0): students[lcv].set_index(index) # once the index is found, stores index in student object and exists loop break # 2. Students that misspelled name for index in range(len(students)): if(students[index].get_index() == None): # finds a student that mispelled name firstName = students[index].get_name().split()[0] # splits the student's first name lastName = students[index].get_name().split()[1] # splits the student's last name for count in range(len(studentDatabase)): # checks student database for most similar match firstName_Compare = studentDatabase[count][0].split()[0] # first name of the student being compared lastName_Compare = studentDatabase[count][0].split()[1] # last name of the student being compared if(firstName[0:3] == firstName_Compare[0:3] and lastName[0:3] == lastName_Compare[0:3]): # compares the first three letters of the first and last name for a match students[index].set_name(studentDatabase[count][0]) # sets the correct name students[index].set_index(count) # sets the correct index # 3. Students that entered incorrect ID for index in range(len(students)): if(students[index].get_ID().isnumeric()): # determines if the ID is the student's 10-digit Purdue ID correctID = studentDatabase[students[index].get_index()][1] # finds the correct ID in the student database students[index].set_ID(correctID) # corrects the ID that was originally in the survey # 4. Students that entered incorrect email for index in range(len(students)): if('@purdue.edu' not in students[index].get_email()): # determines if the email is not the student's Purdue email correctEmail = studentDatabase[students[index].get_index()][2] # finds the correct email in the student database students[index].set_email(correctEmail) # corrects the email that was originally in the survey # 5. Students that entered incorrect major for index in range(len(students)): if(len(students[index].get_major()) < 4): # determines if the major is an abreviation correctMajor = studentDatabase[students[index].get_index()][3] # finds the correct major in the student database students[index].set_major(correctMajor) # corrects the major that was originally in the survey #################################################################################################################### # After all corrections, write the first 110 students in each section who filled out survey to two different files # #################################################################################################################### wednesday = open("wednesday.txt", "w") # creates a Wednesday text file that stores students for its section thursday = open("thursday.txt", "w") # creates a Thursday text file that stores students for its section # classification years classification = {"Freshman": 0, "Sophomore": 0, "Junior": 0, "Senior": 0} # majors majors = {"First Year Engineering": 0, "Mechanical Engineering": 0, "Nuclear Engineering": 0, "Chemical Engineering": 0, "Interdisciplinary Engineering": 0, "Aeronautical & Astronautical Engineering": 0, "Electrical & Computer Engineering": 0, "Multidisciplinary Engineering": 0, "Enviornmental & Ecological Engineering": 0, "Biomedical Engineering": 0, "Materials Engineering": 0, "Civil Engineering": 0, "Construction Engineering Management": 0} # Updates the first 110 students in Wednesday section count = 0 index = 0 while(count < 110): # collets the attributes to be printed to the file studentName = students[index].get_name() studentID = students[index].get_ID() studentEmail = students[index].get_email() studentMajor = students[index].get_major() studentYear = students[index].get_year() if(students[index].get_section() == 'Wednesday'): # prints student information to Wednesday section wednesday.write('{0:25}{1:25}{2:35}{3:45}{4}\n'.format(studentName, studentID, studentEmail, studentMajor, studentYear)) count = count + 1 # increments count # records the statistics for class year classification[students[index].get_year()] = classification.get(students[index].get_year(), 0) + 1 # records the statistics for major majors[students[index].get_major()] = majors.get(students[index].get_major(), 0) + 1 index += 1 # increments the index # Updates the first 110 students in Thursday section count = 0 index = 0 while(count < 110): # collets the attributes to be printed to the file studentName = students[index].get_name() studentID = students[index].get_ID() studentEmail = students[index].get_email() studentMajor = students[index].get_major() studentYear = students[index].get_year() if(students[index].get_section() == 'Thursday'): # prints student information to Thursday section thursday.write('{0:25}{1:25}{2:35}{3:45}{4}\n'.format(studentName, studentID, studentEmail, studentMajor, studentYear)) count = count + 1 # increments count # records the statistics for class year classification[students[index].get_year()] = classification.get(students[index].get_year(), 0) + 1 # records the statistics for major majors[students[index].get_major()] = majors.get(students[index].get_major(), 0) + 1 index += 1 # increments the index wednesday.close() # closes the wednesday file thursday.close() # closes the thursday file ############################################################################### # Create two charts that show statistics of the students in the Python course # ############################################################################### # Creation of bar graph for year distribution of students plt.bar(range(len(classification)), classification.values(), align='center') plt.xticks(range(len(classification)), list(classification.keys())) # creates the labels for the bar graph plt.title('Year Distribution of Students') plt.xlabel('Classification Year') plt.ylabel('Number of Students') plt.show() plt.savefig('yearDistribution.png') # saves the figure plt.close() # closes the figure
import student as st import mentor as mr def separator(): print('=' * 60) student1 = st.Student('Vasya', 'Pupkin', 'male') student2 = st.Student('Pupka', 'Vasina', 'female') lecturer1 = mr.Lecturer('Mr', 'Prepod') lecturer2 = mr.Lecturer('Mrs', 'Uchilka') reviewer1 = mr.Reviewer('Mr', 'Review1') reviewer2 = mr.Reviewer('Mrs', 'Review2') student1.courses_in_progress += ['Python'] + ['GIT'] student2.courses_in_progress += ['Python'] student1.finished_courses += ['English'] student2.finished_courses += ['GIT'] lecturer1.courses_attached += ['Python'] + ['GIT'] lecturer2.courses_attached += ['Python'] reviewer1.rate_hw(student1, 'Python', 7) reviewer2.rate_hw(student1, 'Python', 6) reviewer1.rate_hw(student1, 'GIT', 10) reviewer2.rate_hw(student1, 'GIT', 10) reviewer1.rate_hw(student2, 'Python', 9) reviewer2.rate_hw(student2, 'Python', 8)
def add_student(self, no, name, surname, remark): self._student_list.append(student.Student(no, name, surname, remark))
#!/usr/bin/env python3 import student ray = student.Student('David','0987654321','CTY') print(ray.displayStudent())
import pickle,student f = open("student.dat", "wb") student = student.Student(1, "Paula", 9) # Arguments: Object to serialize and file pickle.dump(student, f) f.close()
import calculator # We are importing calculator.py as a module here. We skip .py form the filename import student result = calculator.add(2, 4) print(result) result = calculator.multiply(2, 4) print(result) s1 = student.Student("Lily", 20) # package / module name DOT method / class name # result = add(2, 4) This throws an error. Because add is searched for in the same file c1 = student.Classroom("Class X") student.print_all(s1, c1) print(student.SCHOOL_NAME)
import student import qualification_calculator x = student.Student("Pawel", "Miry", "91081001334") print(x) res = qualification_calculator.QualificationCalculator(x.get_exam_results(), "Informatyka Stosowana") print(res.get_points()) print(qualification_calculator.QualificationCalculator(x.get_exam_results(), "Informatyka Stosowana")) print(qualification_calculator.QualificationCalculator(x.get_exam_results(), "Ekonomia")) print(qualification_calculator.QualificationCalculator(x.get_exam_results(), "Zarzadzanie")) print("#####################################################") #y = student.Student("Twoja", "Matka", "02271409862") #print(y) #print(qualification_calculator.QualificationCalculator(y.get_exam_results(), "computer_science")) #print(qualification_calculator.QualificationCalculator(y.get_exam_results(), "economics")) #print(qualification_calculator.QualificationCalculator(y.get_exam_results(), "management"))
import pickle, student f = open("student.dat", "wb") s = student.Student(112, "Umair", 95) pickle.dump(s, f) f.close()
import student # Create 'student', an Instance of Student() mark = student.Student('Mark', '123') james = student.HighSchoolStudent('James', '222') print(james.get_school_name()) print(mark)
def __init__(self): #create a list of student Object #self__list_student will store object of Student class self.__list_student = [] self.__list_job = [] self.__list_settings = [] self.__list_profiles = [] #add title for the student_data.csv if not os.path.isfile(FILENAME): with open(FILENAME,"w") as file: writer_csv = csv.writer(file) writer_csv.writerow(("User_Name","Password","First_Name","Last_Name")) #add data from student_data.csv to __self.__list_student with open(FILENAME,"r") as file: reader_csv = csv.reader(file) for row in reader_csv: if row != []: self.__list_student.append(s.Student(row[0], row[1], row[2], row[3])) #add title for the job_data.csv if not os.path.isfile(FILENAME_JOB): with open(FILENAME_JOB,"w") as file: writer_csv = csv.writer(file) writer_csv.writerow(("Title","Description","Employer","Location","Salary","Post_Name")) #add data from job_data to __self.__list_job with open(FILENAME_JOB,"r") as file: reader_csv = csv.reader(file) for row in reader_csv: if row != []: self.__list_job.append(j.Job(row[0], row[1], row[2], row[3], row[4], row[5])) #add title for the settings.csv if not os.path.isfile(FILENAME_STG): with open(FILENAME_STG,"w") as file: writer_csv = csv.writer(file) writer_csv.writerow(("user", "email_notif","sms_notif","targeted_ads","language")) #add data from settings.csv to __self.__list_settings with open(FILENAME_STG,"r") as file: reader_csv = csv.reader(file) for row in reader_csv: if row != []: self.__list_settings.append(stg.Settings(row[0], row[1], row[2], row[3], row[4])) #add title for the profiles.csv if not os.path.isfile(FILENAME_PRO): with open(FILENAME_PRO,"w") as file: writer_csv = csv.writer(file) writer_csv.writerow(("user", "title","major","university","bio", "experience", "education")) #add data from profiles.csv with open(FILENAME_PRO,"r") as file: reader_csv = csv.reader(file) for row in reader_csv: if row != []: self.__list_profiles.append(pro.Profiles(row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
import student import ChineseChef student1 = student.Student("John", "Business", 3.2, False) student2 = student.Student("George", "Information Technology", 3.8, True) ChineseChef.chineseChef.make_chicken('A') ChineseChef.chineseChef.make_troll('A') print(student1.gpa)
import pickle,student f = open("student.dat","wb") s = student.Student(123,"john",90) pickle.dump(s,f) f.close()
) #This course can have only one student, so you need to register fast c = course.Course("Guzman", "11:00 MWF", "CFA 123", 1, \ "S2020", "A", master.find_course( \ master_course.MasterCourse("History of Jazz", "MUS", "275")) ) d = course.Course("Zaring", "8:00 MWF", "Olin 202", 250, \ "S2020", "A", master.find_course( \ master_course.MasterCourse("Intro to CS", \ "CS", "150")) ) P = student.Student("ZZZZZZx Dikelsky", 404191) i = student.Student("Alex Dikelsky", 404191) j = student.Student("Laura Bailey", 12345) a.add_student(j) a.add_student(P) a.add_student(i) b.add_student(i) b.add_student(j) c.add_student(i) #Alex got into the Jazz class first c.add_student( j) #Laura is in the queue, so she can only enter if Alex drops the class d.add_student(i) print( "This is the list of MasterCourses, simular to those on the Luther Website"
#主模块 import student as stu L = [] s1 = stu.Student("lwb", 22, 90) s2 = stu.Student("tiantian", 20, 89) L.append(s1) L.append(s2) s2.setScore(88) for x in L: print(x)
#!/usr/bin/env python3 import pickle, student file_name = "student.dat" #opens student.dat for binary writing f = open(file_name, "wb") s = student.Student(101, "John", 90) pickle.dump(s, f) f.close()
# create 3 instances of Student class, with different names # create 2 instances of Course, wioth different names and assign students import student students = [] students.append(student.Student('Bill')) students.append(student.Student('Bob')) students.append(student.Student('Jenny')) students[0].recordGrade(100) students[1].recordGrade(75) students[2].recordGrade(92) students[0].recordGrade(95) students[1].recordGrade(50) students[2].recordGrade(93) for student in students: print('Student: ' + student.firstName + ' has ' + str(len(student.grades)) + ' grades, with an average of ' + str(student.average()))