Python Tutorial 19: Python Classes and Methods Homework Examples
Introduction to Lesson 19
Overview of the Tutorial Series
- Paul McQuarter introduces himself and the lesson, emphasizing the importance of learning Python effectively.
- He humorously suggests that viewers should prepare a strong cup of black coffee as "jet fuel" for their learning journey.
Homework Review from Lesson 18
Student Class Assignment
- The lesson focuses on reviewing homework assigned in the previous session, specifically creating a class to track student information.
- Paul encourages honesty among viewers about their ability to complete the homework, inviting comments based on their experiences.
Key Concepts in Object-Oriented Programming
Creating a Student Class
- The assignment involves defining a
Studentclass with attributes such as first name and last name, along with methods for inputting and processing grades.
- Methods discussed include:
- Inputting grades
- Printing grades
- Calculating average grades
- Finding high and low grades for each student.
Implementation Steps in Visual Studio Code
Coding the Student Class
- Paul demonstrates how to create a new Python program named
student_class.pyand begins coding by defining theStudentclass.
- He explains the necessity of an
__init__function to initialize object attributes (first name and last name).
Testing Object Creation
Creating Instances of Students
- Paul creates instances of students (e.g., Joe Evans) and shows how to access their attributes using dot notation.
- He encounters an error due to naming conventions but resolves it by correcting the class name from plural to singular (
Student).
Final Thoughts on Object Persistence
Maintaining State Across Instances
- After creating multiple student objects, he emphasizes that once created, these objects retain their data throughout different operations within the program.
How to Create and Manage Student Grades in Python
Introduction to Class Variables
- The speaker demonstrates accessing class variables without needing to call methods, using
student1.firstto retrieve the first name of a student.
- Emphasizes the importance of understanding classes as they begin programming, indicating this is their first program of the day.
Creating a Grade Input Class
- A new class named
g_inputis defined for handling grade inputs, inheriting properties from existing classes.
- The speaker notes that while creating a student instance, the number of grades does not need to be passed immediately but will be required when calling
g_input.
Managing Grades
- Introduces a variable
self.ngto track the number of grades inputted by students.
- An empty array is created (
self.grades) to store grades, with a loop set up to iterate through the range based onng.
Inputting Grades
- The loop starts at 0 and runs until one less than
ng, ensuring all grades are captured correctly.
- Highlights the necessity of including colons in syntax and prepares for user input for each grade.
Collecting User Input
- The input function prompts users for grades, converting them into floats before storing them in an array.
- Each entered grade (
grd) is appended toself.grades, allowing easy access later.
Testing Grade Input Functionality
- Returns
self.gradesafter collecting inputs so that it can be printed or used elsewhere in the program.
- Sets up testing by assigning a temporary variable (
latest_student) for checking if data retrieval works correctly.
Finalizing Grade Collection Process
- Tests functionality by calling the method on an instance (e.g.,
student1.g_input(4)), requesting four grades from user input.
- Successfully collects multiple grades (e.g., 90, 95, 96, 97), confirming that they are associated with the correct student.
Understanding Student Grades Input and Output
Inputting Grades
- The process begins with the invocation of a method to input grades, which requires calling
g_inputfirst. This establishes that grades can only be accessed after this method is executed.
- After entering grades (e.g., 90, 91, 92, 93), the system recognizes these as variables associated with
student1.grades, demonstrating how data is stored post-input.
Accessing Grades
- There are two methods to retrieve student grades: directly accessing
self.gradesor using a return statement from a function. Both approaches yield the same result but offer flexibility in implementation.
- The speaker illustrates that invoking
student1.g_inputallows for immediate access to grades without needing an intermediary variable liketest_grades.
Printing Grades
- A new method called
print_gradesis defined to display student grades. It does not require parameters since it utilizes previously stored information about the number of grades (self.ng).
- The program tracks the number of grades per student effectively by storing this count in
self.ng, ensuring accurate retrieval regardless of how many students are processed.
Formatting Output
- Within the printing loop, formatted output includes both first and last names alongside their respective grades, enhancing readability and clarity in presentation.
- To improve visual separation between outputs, a blank line is printed after listing all grades for better formatting.
Error Handling and Debugging
- An error occurs when trying to call
print_grades, indicating that it was given an unexpected argument. This highlights the importance of correctly managing method calls and understanding parameter requirements.
- After correcting issues related to passing 'self', successful execution confirms that both grade input and printing functionalities work as intended.
Calculating Average Grades
- The next step involves defining an average calculation method (
av_grades). It emphasizes maintaining state through attributes likeself.ng, which keeps track of how many grades each student has entered.
- A temporary variable (
bucket) is introduced for summing up individual grades before calculating averages, showcasing efficient memory management without unnecessary persistence of data.
How to Calculate Average Grades in Python
Setting Up the Grade Calculation
- The speaker discusses using a loop (
for i in range) to iterate through grades, emphasizing the need forself.ngto account for varying numbers of grades among students.
- A floating-point number is required for grades (e.g., 91.5), and the speaker mentions needing to input these values correctly.
Calculating the Average
- To calculate average grades, all grades are summed up in a variable called
bucket, which is updated with each grade fromself.grades[i].
- The importance of using
selfis highlighted, ensuring that when different student instances are called, their respective grades are accessed correctly.
Returning and Storing Averages
- After summing the grades, the average is calculated by dividing
bucketbyself.ng. The speaker considers two methods: storing it as an instance variable or returning it directly.
- The preference leans towards returning the average directly for simplicity and clarity.
Printing Student Information
- The process of creating student instances and printing their grades is outlined. An example shows how to call methods like
student1.avg_grades()to retrieve averages.
- The speaker emphasizes formatting output correctly, including concatenating strings properly to avoid spacing issues in printed results.
Inputting Grades and Displaying Results
- An example interaction demonstrates entering four grades (90, 91, 92, 93), leading to a successful calculation of Joe Evans's average grade displayed as "Joe has an average of 91.5."
Formatting Output Correctly
- Attention is drawn to formatting issues where extra spaces appear; solutions involve string concatenation adjustments.
- Further testing confirms that proper formatting leads to clear outputs without unnecessary spaces.
Finding High and Low Grades
Initializing High and Low Grades
- The next step involves defining a method named
high_low, initializing high and low grade variables appropriately—high initialized at zero and low at one hundred—to ensure accurate comparisons during calculations.
Iterating Through Grades
- A loop iterates through all entered grades (
for i in range(0, self.ng)), allowing comparison against initialized high/low values. This sets up for determining both highest and lowest scores effectively.
Understanding Grade Calculation in Python
Logic for Determining High and Low Grades
- The logic checks if the current grade is greater than the high grade. If true, it updates the high grade to the current grade.
- Conversely, if the current grade is less than the low grade, it updates the low grade to reflect this new lower value.
- Instead of storing high and low grades as class attributes, they are returned directly from a function for immediate use.
Implementing Return Values
- When returning two values (low and high grades), they are assigned to variables
low_gandhigh_gfor further processing.
- The program prints out student information including their first name along with their calculated high and low grades.
Debugging Issues
- An error occurs when trying to access an undefined variable
high_grade, which highlights common pitfalls in coding such as typos.
- Another issue arises due to incorrect indentation that causes a variable not to be recognized within its intended scope.
User Input Enhancements
- After successfully running the program, user input prompts are refined for clarity. For example, instead of generic prompts, specific instructions like "please enter Joe's first grade" are implemented.
- Suggestions are made to improve user experience by clarifying what grades need to be entered during input.
Final Adjustments and Testing
- A final adjustment involves concatenating strings correctly so that user prompts display accurately without syntax errors.
- The code encounters a type conversion error when attempting to convert string inputs into floats; debugging efforts focus on ensuring proper data types during input collection.
Grade Calculation and Reporting Process
Initial Setup and Input
- The speaker demonstrates entering grades for a student named Joe, resulting in an average of 91.5, with a high of 93 and a low of 90.
- The speaker tests copying and pasting code to troubleshoot an earlier error, confirming that the input works correctly now.
- The speaker expresses excitement about the functionality of the program while preparing to add more students.
Adding Multiple Students
- Introduction of two students: Joe Evans (with four grades) and Shirley (with six grades), indicating different workloads.
- The speaker outlines plans to create reports for both students after inputting their respective grades.
Generating Reports
- A print statement is prepared for generating a grade report for Joe Evans, using his first and last name from the student object.
- Discussion on how to print grades without needing additional print statements by calling
student_one.print_grades().
- The average grade calculation is confirmed as being returned from the method
ab_grades().
Finalizing Outputs
- The speaker details how to display both low and high grades alongside averages in the report format.
- After entering Joe's grades successfully, Shirley's higher performance is noted with her receiving multiple high scores.
Troubleshooting Issues
- A typo in referencing "student one" is acknowledged; adjustments are made to ensure correct function calls during printing.
Comprehensive Grade Reporting
- Both students' grade reports are generated successfully, showcasing their individual performances clearly.
- Confirmation that Joe's report displays correctly with all relevant statistics following successful inputs.
This structured approach captures key moments from the transcript while providing timestamps for easy reference.
Grade Calculation and Class Methods
Understanding Grade Averages
- The average grade is calculated as 91.5, with a low of 90 and a high of 93.
- For Shirley Baker, her grades are listed as 86, 99, 97, 99, and 98; resulting in an average of 96.5, a low of 86, and a high of 100.
Key Concepts in Object-Oriented Programming
- The
__init__method initializes the student object by setting up variables passed during creation.
- Once a student object (e.g.,
student1) is created, various methods can be called using dot notation (e.g.,student1.method()).
Homework Assignment
- Students are encouraged to complete their homework from scratch without referencing previous work or videos to ensure understanding.
Upcoming Lessons on Threading and Graphics
Introduction to Threading
- The next lesson will focus on threading concepts necessary for Arduino projects where multiple processes may run simultaneously.
Transition to Graphics Programming
- Following threading lessons, the course will shift towards creating advanced graphics and animations in Python.
- This new playlist will cover visual programming techniques that could be applied in game development or other creative projects.
Engagement with Content
- Viewers are encouraged to engage with the content by liking the video, subscribing for updates, and sharing on social media.