Fundamentals 15 min read

Python Fundamentals: Standard Libraries, Data Types, Context Managers, and Common Practices

This article presents a comprehensive Python fundamentals guide covering common standard libraries, built‑in data types, the with statement, mutable vs immutable types, date handling, word counting, file deletion, custom exceptions, error handling, bug‑fix strategies, and key language feature differences between Python 2 and 3.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Fundamentals: Standard Libraries, Data Types, Context Managers, and Common Practices

1. List five commonly used Python standard libraries.

import os
import sys
import re
import math
import time
import datetime
import random
import threading
import multiprocessing

2. Built‑in data types in Python.

int, float, complex  # numeric types
bool                # boolean
str                 # string
list                # list
tuple               # tuple
dict                # dictionary

3. What does the with statement do when opening a file?

The with statement ensures that resources are automatically cleaned up (e.g., files are closed, locks are released) even if an exception occurs. It works via a context manager object that implements __enter__ and __exit__ methods.

with context_expression [ as target]: with‑body

4. Mutable and immutable data types in Python.

Immutable types: numbers, strings, tuples. Mutable types: lists, dictionaries, sets.

5. Get the current date in Python.

# -*- coding: UTF-8 -*-
import datetime
import time

if __name__ == "__main__":
    print(time.time())                                 # timestamp
    print(time.strftime("%Y-%m-%d %H:%M:%S %w", time.localtime()))  # formatted time
    print(datetime.datetime.now())                    # current datetime

6. Count the occurrence of each word in a string.

def word_amount(sentence):
    split_list = sentence.split()
    dict_result = {}
    for word_name in split_list:
        if word_name not in dict_result:
            dict_result[word_name] = 1
        else:
            dict_result[word_name] += 1
    return dict_result

if __name__ == '__main__':
    sentence = "I can because i think i can"
    dict_result = word_amount(sentence)
    print(dict_result)

Alternative using collections.Counter :

from collections import Counter
if __name__ == '__main__':
    sentence = "I can because i think i can"
    counts = Counter(sentence.split())
    print(counts)

7. Delete a file using Python and using a Linux command.

import os
os.remove("demo.txt")
rm demo.txt

8. Write a custom exception.

class printException(Exception):
    pass

def testRaise():
    raise printException('printErr')

if __name__ == '__main__':
    try:
        testRaise()
    except printException, e:
        print e

9. Explain try , except , else , finally .

def read_filedata(file_name):
    file_obj = ""
    try:
        file_obj = open(file_name, "r")
        result_data = file_obj.read()
    except IOError, e:
        file_obj = "File not found: " + str(e)
    else:
        return result_data
    finally:
        if isinstance(file_obj, str):
            return file_obj
        elif isinstance(file_obj, file):
            file_obj.close()
        else:
            return "Unknown error, please check your code..."

if __name__ == '__main__':
    result = read_filedata("abc.txt")
    print(result)

10. How to handle bugs.

First read the error message and locate the problematic code; most bugs are due to data‑structure or algorithm mistakes. If the cause is not obvious, use the debugger or insert breakpoints. When still stuck, search the error online or discuss with teammates, but be mindful of their time.

Language Features

1. Understanding Python and its differences from other languages.

Python is a concise, powerful, dynamically typed, portable, extensible, and embeddable interpreted language with a rich third‑party ecosystem.

Strong‑type vs weak‑type languages.

Strong‑type languages (e.g., Python, Java, C++) rarely perform implicit type conversion, reducing accidental errors; weak‑type languages (e.g., JavaScript, PHP) allow more implicit conversions.

Dynamic vs static languages.

Dynamic languages perform type checking at runtime (Python, Ruby), while static languages check types at compile time (C, Java).

Compiled vs interpreted languages.

Compiled languages translate source code to machine code before execution (C/C++), whereas interpreted languages execute source line‑by‑line via an interpreter (Python), offering cross‑platform ease at the cost of runtime overhead.

Python interpreter types.

CPython – the standard implementation written in C. IPython – an enhanced interactive shell built on CPython. PyPy – a JIT‑enabled interpreter offering speed gains. Jython – runs on the JVM, compiling Python to Java bytecode.

Key differences between Python 2 and Python 3.

Default encoding: Python 2 uses ASCII, Python 3 uses UTF‑8.

String handling: Python 2 separates str (bytes) and unicode ; Python 3 uses str for Unicode text and bytes for raw data.

print is a statement in Python 2, a function in Python 3.

Import semantics: Python 2 prefers relative imports, Python 3 defaults to absolute imports.

input returns str in Python 3; in Python 2, input evaluates the input, raw_input returns a string.

Division: / performs integer division in Python 2, true division in Python 3; // is floor division in both.

Integer types: Python 2 has int and long ; Python 3 has a unified int type.

Boolean literals: True and False are constants in Python 3, mutable globals in Python 2.

Iterators: many built‑ins return iterators in Python 3 (e.g., range , dict.keys() ).

Nonlocal keyword: introduced in Python 3 to modify variables in enclosing scopes.

LEGB scope rules: local → enclosing → global → built‑in, with global and nonlocal controlling access.

Exception HandlingData Typesfundamentalsstandard-libraryContext ManagerPython2 vs Python3
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.