CodeBlanks Logo Icon CodeBlanks

Business logic

Write business rules with functions and conditions.

Business logic: compute the average

In this lesson you will compute the average of the grades. sum(grades) gives the total, len(grades) the count; division yields the average:

average = sum(grades) / len(grades)
print("ortalama:", average)
# ortalama: 87.0

The starting code includes the previous lessons' solutions. You will add the average calculation and print. Since grades is now [85, 90, 78, 95], the average is 87.0.

This is the fundamental way to summarise data.

Practice Compute and print the average

Write average = sum(grades) / len(grades). Then write print("ortalama:", average).

Starter code

main.py
# Grade calculator - grades list
grades = [85, 90, 78]
print(grades)
grades.append(95)
print("eklendi:", len(grades))
# compute and print the average

Sample solution

main.py
grades = [85, 90, 78]
print(grades)
grades.append(95)
print("eklendi:", len(grades))
average = sum(grades) / len(grades)
print("ortalama:", average)

Expected output

[85, 90, 78]
eklendi: 4
ortalama: 87.0

Next step: error handling

The business logic is ready — you can compute the average. But what if the grades list is empty? len([]) is zero and division by zero raises ZeroDivisionError. In the next lesson you will guard against this with try/except.

This layer will let the app handle error cases without crashing. Robust code anticipates errors and is prepared for them. Each lesson builds on top of the previous one.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the average computed?

  • sum(grades) * len(grades)
  • sum(grades) - len(grades)
  • len(grades) / sum(grades)
  • sum(grades) / len(grades) Correct answer

Explanation: Average = total / count. sum(grades) / len(grades).

2 Match business logic

Term Meaning
sum(grades) Total
len(grades) Count
/ Division
average Result variable

3 Complete the average calculation

Question
average = ____ / len(grades)
Answer
average = sum(grades) / len(grades)

Explanation: sum(grades) gives the total of the grades.

All lessons in Beginner