PYTHON LESSON

Topic 51/63 · Phase 6: Advanced Engineering

Context Managers — Python lesson on EduBard (phase: Advanced Engineering)

Context Managers

Main idea

with ensures setup and cleanup around a block.

Tip

Use for files/resources.

Watch out

Leaking file handles without with.

Read this next

This lesson is about Context Managers. You are in the Advanced Engineering part of the course.

Main idea:
with ensures setup and cleanup around a block.

How to learn it: type a very small program first. Run it. Change one line and run again.

Tip:
Use for files/resources.

Common mistake:
Leaking file handles without with.

Your challenge:
Read and write file using with.

Scroll down to the challenge lab. Run your code there. When the output meets the task and the checks pass, press the green button to finish this topic.

Example code

Copy this example if it helps. Change it so it matches Context Managers.

# Topic: Context Managers
def main():
    sample = "edit me"
    # TODO: apply Context Managers concept here
    result = sample
    print("Result:", result)

if __name__ == "__main__":
    main()

Challenge

Read and write file using with.

Before you can finish: your output should include at least 16 characters; at least 1 non-empty line(s); no crash traceback—fix errors until the program runs cleanly.

Use Run. Read the output. Change your code until the task is done.

Starter reference

# Challenge starter for Context Managers
def solve():
    # Write your solution here
    pass

print("Update solve() and run")

Your code

The first Run may load Python in your browser (one-time). Later runs are faster.



    
    

Navigation