DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on • Updated on

🤔 Python Quiz: `with` or without?

Follow me to learn 🐍 Python in 5-minute a day fun quizzes!

The with statement in Python is a powerful feature for managing the lifetime of resources, ensuring they are properly acquired and released, thus promoting cleaner and more reliable code. It's primarily used in scenarios where a pair of related operations need to be executed, such as opening and closing a file, or acquiring and releasing a lock.

Quiz

Sample 1

file = open('example.txt', 'r')
content = file.read()
print(content)
Enter fullscreen mode Exit fullscreen mode

Sample 2

# Using 'with' statement for file operations
with open('example.txt', 'r') as file:
    content = file.read()
print(content)
Enter fullscreen mode Exit fullscreen mode

Post your answer in the comments – is it 0 for the first sample or 1 for the second! As usual, the correct answer will be explained in the comments.

Top comments (0)