dev.rean.me
python

25. 15 Best Python Libraries for Beginners with Examples and Tips

Learn the 15 best Python libraries for beginners — math, random, datetime, json, pathlib, turtle, tkinter, requests, NumPy, pandas, Matplotlib, Pillow, Beautiful Soup, Pygame, and Flask — with simple examples, install commands, and tips.

2026-11-04 · 9 min read

Share:

Hello friend! 👋 A library (or module) is code that other people already wrote for you. Instead of writing everything from zero, you just import it and use it. This is the real power of Python! 🐍

In this post, you learn 15 libraries that are great for beginners. Each one has a short example you can run right away.

Two Kinds of Libraries

  • 📦 Built-in (standard library): Come with Python. No install needed. Just import.
  • ⬇️ Third-party: Made by the Python community. Install first with pip.

Install all 8 third-party libraries in this post with one command:

pip install requests numpy pandas matplotlib pillow beautifulsoup4 pygame flask

On Windows, if pip does not work, try:

py -m pip install requests

Quick Overview

#LibraryInstall?Use it for
1mathBuilt-inMath functions
2randomBuilt-inRandom numbers, games
3datetimeBuilt-inDate and time
4jsonBuilt-inSave and read data
5pathlibBuilt-inFiles and folders
6turtleBuilt-inDraw shapes
7tkinterBuilt-inDesktop app with window
8requestspip install requestsGet data from the internet
9numpypip install numpyFast number calculation
10pandaspip install pandasTables, Excel, CSV data
11matplotlibpip install matplotlibCharts and graphs
12Pillowpip install pillowEdit images
13Beautiful Souppip install beautifulsoup4Read data from websites
14pygamepip install pygameMake 2D games
15Flaskpip install flaskMake websites

📦 Built-in Libraries

1. math — Math Functions

Square root, pi, round up, round down, and more.

import math

print(math.sqrt(16))    # 4.0
print(math.pi)          # 3.141592653589793
print(math.ceil(4.2))   # 5  (round up)
print(math.floor(4.8))  # 4  (round down)

radius = 3
area = math.pi * radius ** 2
print(round(area, 2))   # 28.27

2. random — Random Numbers

Great for games, quizzes, and picking random items.

import random

print(random.randint(1, 6))      # roll a dice: 1 to 6

fruits = ["apple", "banana", "mango"]
print(random.choice(fruits))     # pick one fruit

random.shuffle(fruits)           # mix the list
print(fruits)

Mini project — guess the number:

import random

secret = random.randint(1, 10)
guess = int(input("Guess a number from 1 to 10: "))

if guess == secret:
    print("Correct! 🎉")
else:
    print(f"Wrong! The number was {secret}.")

3. datetime — Date and Time

Get today's date, add days, and format dates.

from datetime import date, datetime, timedelta

today = date.today()
print(today)                        # e.g. 2026-11-04
print(today + timedelta(days=7))    # one week later

now = datetime.now()
print(now.strftime("%d/%m/%Y %H:%M"))  # e.g. 04/11/2026 09:30

birthday = date(2000, 5, 20)
print((today - birthday).days, "days old")

4. json — Save and Read Data

JSON is a common format to save data and send data between apps.

import json

student = {"name": "Dara", "age": 20, "skills": ["Python", "SQL"]}

# Save to a file
with open("student.json", "w", encoding="utf-8") as f:
    json.dump(student, f, indent=2)

# Read from the file
with open("student.json", encoding="utf-8") as f:
    data = json.load(f)

print(data["name"])     # Dara
print(data["skills"])   # ['Python', 'SQL']

5. pathlib — Files and Folders

Create folders, write files, and find files in an easy way.

from pathlib import Path

folder = Path("my_notes")
folder.mkdir(exist_ok=True)          # create folder if not exist

file = folder / "hello.txt"          # my_notes/hello.txt
file.write_text("Hello Python!", encoding="utf-8")

print(file.read_text(encoding="utf-8"))  # Hello Python!
print(file.exists())                     # True

for py_file in Path(".").glob("*.py"):   # list all .py files
    print(py_file.name)

6. turtle — Draw Shapes

A fun way to learn loops. A small turtle draws on the screen when you move it.

import turtle

t = turtle.Turtle()
t.color("blue")
t.pensize(3)

# Draw a star
for _ in range(5):
    t.forward(150)
    t.right(144)

turtle.done()

7. tkinter — Desktop App with a Window

Build simple apps with buttons and text boxes.

import tkinter as tk

def say_hello():
    label.config(text=f"Hello, {entry.get()}! 👋")

root = tk.Tk()
root.title("My First App")

entry = tk.Entry(root, width=25)
entry.pack(padx=20, pady=10)

tk.Button(root, text="Say Hello", command=say_hello).pack()

label = tk.Label(root, text="")
label.pack(pady=10)

root.mainloop()

⬇️ Third-Party Libraries (Install with pip)

8. requests — Get Data from the Internet

Download web pages or call an API in one line.

pip install requests
import requests

response = requests.get("https://api.github.com/users/python")
print(response.status_code)   # 200 means OK

data = response.json()
print(data["name"])
print(data["public_repos"], "public repositories")

9. numpy — Fast Number Calculation

Work with many numbers at once. Used in data science and AI.

pip install numpy
import numpy as np

scores = np.array([80, 95, 70, 88])

print(scores.mean())   # 83.25
print(scores.max())    # 95
print(scores + 5)      # [ 85 100  75  93]  add 5 to every score

10. pandas — Work with Tables (Excel, CSV)

Like Excel, but with code. Very popular for data analysis.

pip install pandas
import pandas as pd

df = pd.DataFrame({
    "name": ["Dara", "Sok", "Vuth"],
    "score": [85, 92, 78],
})

print(df)
print(df["score"].mean())     # 85.0
print(df[df["score"] > 80])   # only students with score over 80

df.to_csv("scores.csv", index=False)   # save to CSV file

To read an Excel file, use pd.read_excel("file.xlsx") (also run pip install openpyxl).

11. matplotlib — Charts and Graphs

Turn numbers into a picture.

pip install matplotlib
import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
hours = [1, 2, 1.5, 3, 2]

plt.plot(days, hours, marker="o")
plt.title("My Python Study Hours")
plt.xlabel("Day")
plt.ylabel("Hours")
plt.show()

Change plt.plot to plt.bar to make a bar chart.

12. Pillow — Edit Images

Resize, convert, and save photos. Install name is pillow, but import name is PIL.

pip install pillow
from PIL import Image

img = Image.open("photo.jpg")
print(img.size)                 # (width, height)

small = img.resize((300, 200))
small.save("photo_small.jpg")

gray = img.convert("L")         # black and white
gray.save("photo_gray.jpg")

13. Beautiful Soup — Read Data from Websites

Get titles, links, and text from a web page (web scraping). Use it together with requests. Install name is beautifulsoup4, import name is bs4.

pip install beautifulsoup4
import requests
from bs4 import BeautifulSoup

html = requests.get("https://example.com").text
soup = BeautifulSoup(html, "html.parser")

print(soup.title.text)          # Example Domain

for link in soup.find_all("a"):
    print(link.get("href"))

14. pygame — Make 2D Games

Make your own game with images, sound, and keyboard control.

pip install pygame
import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("My First Game")
clock = pygame.time.Clock()

x = 200
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x -= 5
    if keys[pygame.K_RIGHT]:
        x += 5

    screen.fill((30, 30, 30))
    pygame.draw.circle(screen, (0, 200, 255), (x, 150), 20)
    pygame.display.flip()
    clock.tick(60)               # 60 frames per second

pygame.quit()

Use the left and right arrow keys to move the ball.

15. Flask — Make a Website

Build a small website or web API with only a few lines.

pip install flask
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Flask! 🐍"

@app.route("/hello/<name>")
def hello(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    app.run(debug=True)

Run the file, then open http://127.0.0.1:5000 in your browser. Try http://127.0.0.1:5000/hello/Dara too.


🗺️ Which Library to Learn First?

You want to…Start with
Practice loops in a fun wayturtle, random
Make a desktop apptkinter
Make a gamepygame
Work with data, Excel, chartspandas, numpy, matplotlib
Get data from the internetrequests, Beautiful Soup
Make a websiteFlask
Automate files and photospathlib, json, Pillow

💡 Tips

  • Learn the built-in libraries first. They need no install and are used everywhere.
  • Don't name your file the same as a library! A file called random.py or turtle.py will break import random or import turtle.
  • Some libraries have a different install name and import name: pip install pillow → import PIL, pip install beautifulsoup4 → import bs4.
  • Use a virtual environment for each project, so libraries don't mix: python -m venv venv.
  • Save your project's libraries with pip freeze > requirements.txt, and install them again with pip install -r requirements.txt.
  • See what you already installed with pip list.
  • Use common short names like everyone else: import numpy as np, import pandas as pd, import matplotlib.pyplot as plt.
  • Always add encoding="utf-8" when you read or write text files, especially for Khmer text.
  • Only scrape websites that allow it, and don't send too many requests too fast.
  • Read the official docs and search library name + example — every popular library has many free examples.

Conclusion

Libraries let you do big things with small code: draw, make games, build apps and websites, and work with data. Start with the built-in ones, then install one third-party library that fits what you want to build. Try every example, change it, and make it your own. Happy coding! 🐍

← Back to python
Share: