Home Practicum 1 Practicum 2 Practicum 3 Practicum 4

Welcome to Practicum 4!

Let's start with a recap of for loops. Complete the quizes below (they are anonymous and not graded), and we'll discuss the answers immediately in class. Please do one at a time (you have 5 minutes for each), wait for the discussion and only do the next one when everybody is ready!

  1. Quiz 1
  2. Quiz 2
  3. Quiz 3

Functions

During the lecture you were introduced to the concept of functions. The correct use of functions will make your code much easier to:

Have a look at these code samples. They both calcuate and print the GPA of two students, given their grades and the subject weights.

Example 1:
student_1_grades = [10, 12, 9]
student_2_grades = [11, 13, 8]
weights = [0.2, 0.3, 0.5]

student_1_gpa = 0
for idx in range(len(weights)):
    student_1_gpa += weights[idx]*student_1_grades[idx]
print(student_1_gpa)

student_2_gpa = 0
for idx in range(len(weights)):
    student_2_gpa += weights[idx]*student_2_grades[idx]
print(student_2_gpa)
Example 2:
student_1_grades = [10, 12, 9]
student_2_grades = [11, 13, 8]
weights = [0.2, 0.3, 0.5]

def calc_gpa(grades, weights):
    result = 0
    for idx in range(len(weights)):
        result += weights[idx] * grades[idx]
    return result

print(calc_gpa(student_1_grades, weights))
print(calc_gpa(student_2_grades, weights))

In Example 1, the code for calculating the GPA is written twice, even though it's basically the same. In Example 2, we created the function for calculating the GPA and then we can use it as many times as we want.

We can test that calc_gpa works by giving it different values without having to run all the rest of the code.

When somebody reads this code they can skip the actual implementation of the GPA calculation and go directly to what the code is doing and read it in plain English: print the calculated gpa of student_1 and then of student_2.

What to always remember about functions

Time for Quiz 4!

Excercise 1

Download pr04.py file. There are a few functions whose definitions are empty and you'll need to implement them. Do not modify anything in the main() function. Do not modify the argument lists of the functions, only implement their bodies.