Back to Python
2026-02-135 min read

Core Modules (Python Programming)

Learn Core Modules (Python Programming) step by step with clear examples and exercises.

Why This Matters

Welcome to our full guide on Python Core Modules! Understanding and mastering these essential built-in libraries is crucial for excelling in exams, interviews, and real-world programming challenges. In this lesson, we delve into the world of Python Core Modules, providing you with a solid foundation for your programming journey.

Python Core Modules are an integral part of the standard Python distribution, offering various functionalities such as handling files, working with dates and times, creating network connections, and more. These built-in libraries provide a wide range of pre-written code that can significantly speed up development time and improve the efficiency of your programs.

Prerequisites

To fully grasp the concepts covered in this lesson, it is assumed that you have a good understanding of Python syntax, variables, functions, loops, and basic data structures like lists and dictionaries. If you are new to Python or need a refresher, consider reviewing our previous lessons on Python Basics before proceeding.

Core Concept

Python Core Modules are pre-installed libraries that provide various functionalities essential for programming tasks. Some of the most commonly used core modules in Python include:

Built-in Modules Overview

  1. math: Provides mathematical functions like sqrt(), sin(), cos(), etc., which are essential for solving various mathematical problems.
  2. os: Handles operating system-related functionalities, such as reading and writing files, listing directories, changing the current working directory, and more.
  3. datetime: Deals with dates and times in Python. It provides functions to manipulate date and time objects, making it easy to work with temporal data.
  4. sys: Contains various system-specific parameters and functions, including path information, standard input/output streams, and more.
  5. random: Generates random numbers using various distributions like uniform, normal, exponential, etc., which are useful for simulations, games, and other applications that require randomness.

Working with Core Modules

To use a core module in your Python script, you simply import it at the beginning of your code. For example:

import math

Using math module functions

print(math.sqrt(16)) # Output: 4.0

print(math.sin(math.pi / 2)) # Output: 1.0

In the example above, we imported the `math` module and used two of its functions: `sqrt()` and `sin()`.

Worked Example

Let's create a simple Python script that demonstrates the use of multiple core modules. This script will read a file, calculate the sine of each line, and write the results to another file.

import os
import math

Read input file

input_file = "input.txt"

with open(input_file, "r") as f:

lines = f.readlines()

Write output file

output_file = "output.txt"

with open(output_file, "w") as f:

for line in lines:

value = math.sin(float(line))

f.write(str(value) + "\n")

Change the current working directory to the one containing this script

os.chdir(os.path.dirname(__file__))

In this example, we imported both `math` and `os` modules. We used the `open()` function from the `os` module to read an input file (`input.txt`) and write the output to another file (`output.txt`). Additionally, we utilized the `chdir()` function from the `os` module to change the current working directory to the one containing this script.

Common Mistakes

  1. Importing a module incorrectly: Make sure you use the correct syntax for importing modules: import . Avoid using from import *, as it can lead to naming conflicts and make your code harder to read.
  2. Using functions from a module without importing it: Before using any function from a module, ensure that you have imported the module correctly.
  3. Not handling exceptions: When working with core modules, especially those dealing with files or network connections, always remember to handle potential exceptions to make your code more robust.
  4. Misusing mathematical functions: Be aware of the arguments and return types of mathematical functions in the math module. For example, the sin() function expects its argument in radians, not degrees.

Common Mistakes - Subheadings

  • Incorrect Import Syntax
  • Using Functions without Proper Imports
  • Not Handling Exceptions
  • Misusing Mathematical Functions

Practice Questions

  1. Write a Python script that uses the datetime module to calculate the current date and time in both ISO format and the local time zone's format.
  2. Create a script that reads a CSV file containing numbers, calculates the average of those numbers using the math module, and writes the result to a new file.
  3. Write a Python program that uses the os module to create a new directory named "my_directory" in the current working directory.
  4. Write a script that generates 10 random integers between 1 and 100 using the random module and stores them in a list. Then, calculate the sum of these numbers.

Practice Questions - Subheadings

  • Date and Time Calculation
  • Average Calculation from CSV File
  • Creating a New Directory
  • Generating Random Numbers and Calculating Sum

FAQ

  1. Why should I use Python Core Modules instead of third-party libraries?
  • Python Core Modules are built into the standard distribution, so they are always available without requiring additional installation steps. They provide essential functionalities that are widely used in programming tasks. Third-party libraries may offer more advanced or specialized features but can require extra setup and maintenance.
  1. What is the difference between importing a module with and without as?
  • When you use import , you access functions or classes directly from the module using their full name (e.g., math.sqrt()). On the other hand, if you use import as alias, you can give the imported module an alias and access its functions using that alias (e.g., import math as m; m.sqrt(16)). Using an alias can make your code more readable by reducing repetition of long module names.
  1. Why is it important to handle exceptions when working with core modules?
  • Handling exceptions helps make your code more robust by allowing you to catch and deal with potential errors that might occur during the execution of your script, such as file not found errors or network connection issues. Proper exception handling can prevent your program from crashing unexpectedly and make it easier to debug any issues that arise.
  1. Can I import a specific function from a module instead of the entire module?
  • Yes, it is possible to import a specific function from a module using the syntax from import . For example: from math import sin allows you to use sin() directly without having to write math.sin(). However, this can lead to naming conflicts if multiple modules have functions with the same name. In such cases, it's recommended to use a different alias or fully qualify the function name (e.g., import math as m; from math import sin as my_sin).
Core Modules (Python Programming) | Python | XQA Learn