LearnFrenzy
Sign in Take a free test

Modules and Packages · Modules and Packages Coding Problems · Question 1

Create and use your own module in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a module lf_marks.py with average() and grade() functions and a __main__ guard, then import it and use it. (The program writes the module to a temporary folder so it runs as one file.)

Solution
main.py Run
import sys, tempfile, pathlib

folder = pathlib.Path(tempfile.mkdtemp())
(folder / "lf_marks.py").write_text('''
def average(marks):
    return sum(marks) / len(marks)

def grade(avg):
    return "A" if avg >= 85 else "B" if avg >= 70 else "C"

if __name__ == "__main__":
    print("self-test:", grade(average([90, 80])))
''')
sys.path.insert(0, str(folder))

import lf_marks
for name, marks in {"Asha": [91, 88, 95], "Ravi": [72, 65, 70]}.items():
    avg = lf_marks.average(marks)
    print(f"{name}: {avg:.1f} -> {lf_marks.grade(avg)}")

Output Verified by running it on Python 3

Asha: 91.3 -> A
Ravi: 69.0 -> C

The self-test line does not run because the module is imported, not executed. Calls use the module prefix lf_marks.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links