Hello and welcome back. My name is Andy, and here we are learning Python.
Introduction: Why Python Uses Modules
We have used in the past many features of Python that are built-in, but of course, the amount of stuff you can put into a language like Python is necessarily limited. You don’t want to bloat your language too much, because if you make the program too big, it takes much longer to install, it takes much longer to run, and so on.
So with Python, they try to keep the core of the language relatively small and the functions that are offered only the most important ones. And then they added a mechanism for how you can include other external modules that extend the functionality of the language with new functions.
So Python has lots of built-in functions like print, int, and input, but for more specialized cases, you just include another module. A module is a separate file containing Python definitions and statements, like a toolkit of pre-written code. Many of these come together with the Python bundle, so most of the modules you will need are already included in Python. But some are also external; you install them separately, and then you can use their functions.
How to Use a Module
To use a module, you must first import it at the top of your script. This makes it available in your script. And later, when you want to use a function from this module, you do it like this: module_name.function_name().
It’s just like calling a method from an object, like we said before. When you have the string object and you call the .upper() method to turn it into uppercase, in this case, it’s a similar syntax where you use the module_name.function_name.
Here you see an example of that:
# We import the math module, which contains advanced mathematical functions.
import math
# Of course, you can do basic arithmetic in Python without this,
# but if you want something more advanced, like square roots, then you can do
# this.
result = math.sqrt(81)
print(result)The math Module: For Advanced Calculations
The math module has lots of other functions for mathematics, for example, rounding functions. Here is the function ceil, which means “ceiling,” which is rounding up a number—taking the next higher integer after a number that has a decimal point.
Here we want to calculate how many pages we need for a particular number of words. So we say we have a total number of words, and then we have the words per page, and so we want to divide them. But you don’t want to have a result that says you need 235.756 pages; this is a little silly because we don’t have decimal fractions of pages. So what we do is to calculate the ceiling of that—the next integer after the number. And so this is what happens here. Let me start it and show you how it works.
import math
total_words = 2357
words_per_page = 300
# This division results in a number with a decimal fraction.
pages_needed = total_words / words_per_page
print(f"Raw calculation: You would need {pages_needed} pages.")
# We use math.ceil() to round up to the next whole number.
required_pages = math.ceil(pages_needed)
print(f"Actually, you will need {required_pages} pages.")The math module generally provides access to common mathematical functions and constants. We already talked about sqrt (the square root) and ceil (the ceiling). There is also, of course, the opposite of the ceiling, which is floor (it rounds down). And then there are also some useful constants in there. math.pi is a constant that holds the value of pi (3.14159...). But there are many, many more. There are often hundreds of functions in one module; you have to go and look at the module documentation, and then you will see all these functions.
The random Module: For Games and Simulations
Another very important module that you might want to use in your programs is random. We often need random numbers. You want to, for example, have some dice, you want to make some simulation that requires a random number, or you want to make a card game—you need some random numbers. Or you want to just pick a random element out of some list.
And this is what the random module does. So you import random, and then you have various functions that allow you to choose, for example, one random element out of a list. And this is what you see here.
import random
# Example 1: Choosing a random element from a list
figures = [”Gandalf”, “Aragorn”, “Frodo”, “Legolas”]
chosen_figure = random.choice(figures)
print(f"The randomly chosen figure is: {chosen_figure}")
# Example 2: Simulating a dice roll with random.randint()
# This gives us a random integer between the two limits, inclusive.
roll = random.randint(1, 6)
print(f"You rolled a {roll}")So let’s execute this, see how it works. No surprises there.
The datetime Module: Working with Dates and Times
The next very useful module is datetime. This allows you to calculate with dates, and dates are hugely important in everyday life. You want to know what weekday is today, for example. You want to know how many days are between two dates, which can be tricky because months have different numbers of days, especially if there’s a February involved.
Here are some things the datetime module can do.
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(f"Current moment is: {now}")
# You can create date objects for specific dates that you want to work with.
# The format is always Year, Month, Day.
date_of_invasion = datetime.date(1944, 6, 6)
end_of_war_in_europe = datetime.date(1945, 5, 8)
# Now I can subtract one date from another.
# Python knows what to do because these are special date objects.
duration = end_of_war_in_europe - date_of_invasion
# The result is a ‘timedelta’ object, from which we can get the number of days.
print(f"The duration between D-Day and V-E Day was {duration.days} days.")
Okay, so this is incredibly convenient if you want to talk about durations. This provides classes for working with dates, times, and time intervals and is crucial for historical research. datetime.datetime.now() returns a datetime object with the current local date and time.
You also have this function strftime (which means “string format time”). You can make a string formatting of a particular date, and you give it the format you want. This is a very powerful function, very flexible, because in this formatting string, you can say how you want it formatted. So in this case, for example, I want it formatted with dashes, and I can do this. And I can format it with two digits, with one digit, in any sequence I want to have the month and the date, and so on.
import datetime
now = datetime.datetime.now()
# We can format the date object into a custom string.
# %Y is the full year, %m is the month number, %d is the day number.
formatted_string = now.strftime("%Y-%m-%d")
print(f"Today’s date, formatted: {formatted_string}")
# Another example with different format codes
# %A is the full weekday name, %B is the full month name.
verbose_format = now.strftime("%A, %B %d, %Y")
print(f"A more verbose format: {verbose_format}")
The os Module: Interacting with the Operating System
A module that’s perhaps less interesting in general for the beginner but sometimes may be very important is os. os is a module that directly interacts with your operating system. This can be more advanced functions, but it can also be something like reading a file. If you want to read a file or save data in a file, then you need the os module.
You also have to be careful when you’re using cloud services like Google Colab. The files you save there are not the same as a local file. For example, Google Colab might make them disappear after a while, depending on your contract, when your session is over. So you have to make sure that you save the data somewhere else; you can save them on your Google Drive or something. But you have to be a little careful about cloud services and the os module. And not all functions may work in Google Colab because, obviously, Google doesn’t want you to mess with their operating system. So these work best, and in the way you expect, on your local machine rather than in this cloud environment, although in many cases it does work. So you can save files on Google Colab; you just need to be careful where you save them and how long they stay there.
Okay, here you see an example. We import os, and then we try to open a file. If we can open the file, we get a success message, and otherwise, we get an error message. And at the end, it tells us where this script is running.
import os
filename = “my_non_existent_file.txt”
try:
# The ‘with’ statement is the recommended way to handle files.
with open(filename, "r") as f:
print(f"Success! We opened the file ‘{filename}’.")
# In a real scenario, you would read the content here.
# content = f.read()
except FileNotFoundError:
print(f"Error: The file ‘{filename}’ could not be found.")
# os.getcwd() gets the “current working directory”
current_directory = os.getcwd()
print(f"This script is currently running from: {current_directory}")Of course, it will not find anything because I don’t have this file, but you can see the messages it gives us.
Okay, that’s it. Thank you and see you next time.


