Basics of Python- My Lesson 5


You’ve made it through our Python Basics revision series with me—Thanks for sticking by and reading my cheat sheets. Welcome to Lesson 5, where we end our cheat sheet series/ revision series whatever you call it of Basics of Python. In this lesson, you’ll learn about:
Inheritance (re‑using and extending classes)
Modules & Packages (organizing and sharing your code)
Generating Random Values (from simple picks to seeded reproducibility)
Working with Directories (navigating, creating, and managing files)
PyPI & pip (installing and publishing Python packages)
INHERITANCE: Mechanism by which a class (child/subclass) reuses code from another class (parent/base class).
# 1. What Is Inheritance?
class Parent:
def greet(self):
print("Hello from Parent")
# Basic inheritance: Child “is a” Parent
class Child(Parent):
pass
c = Child()
c.greet() # → Hello from Parent
# 2. Overriding Parent Methods:
# Redefine methods to change behavior otherwise they stay the same.
class OverridingChild(Parent):
def greet(self):
print("Hello from OverridingChild")
oc = OverridingChild()
oc.greet() # → Hello from OverridingChild
# 3. Calling the Parent Version with super()
class Human:
def __init__(self, name):
self.name = name
def get_species(self):
return "Homo sapiens"
def say(self, msg):
print(f"{self.name}: {msg}")
class Superhero(Human):
species = "Superhuman"
def __init__(self, name, powers=None):
'''Avoid using a list as a default arg—use None + inside check:If you use a mutable
default like a list, every call without an explicit argument will share that same list'''
if powers is None:
powers = ["super strength", "bulletproofing"]
super().__init__(name) # calls Human.__init__ so name is set correctly
self.powers = powers
# Override a parent method
def say(self, msg=None):
return "Dun, dun, DUN!"
# Add entirely new behavior
def boast(self):
for p in self.powers:
print(f"I wield the power of {p}!")
# Instantiate and try it out
sup = Superhero("Tick")
print(sup.get_species()) # → Superhuman
print(sup.say()) # → Dun, dun, DUN!
sup.boast() # → “I wield the power of super strength!” etc.
MODULES: What are Modules? Why is it used?
A single
.py
file grouping related codeBenefits: Name spacing, reuse, clearer organization.
Importing:
import module_name from module_name import func, Class
# Example:
Suppose we have utils.py:
def add(a, b): return a + b
def sub(a, b): return a - b
You can then do:
from utils import add
result = add(3, 4) # result == 7
__all__:
Inside a module, define __all__ to control what gets imported by:
from module_name import *
Example in utils.py:
__all__ = ['add'] # only add() will be imported with '*'
def add(a, b): ...
def sub(a, b): ...
PACKAGES
- A package is a folder (directory) that contains multiple modules (.py files) and has an init.py file inside. This tells Python the folder is a package.
# Example Structure:
mypackage/
__init__.py # Marks the folder as a package
module1.py
subpackage/
__init__.py
module2.py
# Importing from a package:
from mypackage import module1 # Import module1 from mypackage
from mypackage.subpackage import module2 # Import module2 from the subpackage
GENRATING RANDOM VALUES
Module: import random
# Common functions:
random.random() → float ∈ [0.0, 1.0)
random.randint(a, b) → int ∈ [a, b]
random.choice(seq) → random element
random.sample(seq, k) → k unique elements
random.shuffle(list) → in‑place reorder
Dice Question! Lets make a class dice and a function roll and generate random values
import random
class Dice:
def roll(self):
first = random.randint(1,6)
second = random.randint(1,6)
return first, second
dice = Dice()
print(dice.roll())
How it works:
Every time you call dice.roll(), it returns a tuple with two random numbers
between 1 and 6—like rolling two dice.
WORKING WITH DIRECTORIES
# pathlib module (new, cleaner, recommended):
from pathlib import Path
# Make a Path object for a folder or file
p = Path('some/dir') # Specific folder
cwd = Path('.') # Current directory
# Check existence and type
p.exists() # True/False: Does it exist?
p.is_dir() # True/False: Is it a directory?
# Directory operations
p.mkdir(exist_ok=True) # Create directory (no error if it exists)
p.rmdir() # Remove directory (must be empty)
# Find files/directories
# Use glob() to search for files/folders matching a pattern
for item in cwd.glob('*'): # All files and folders in current directory
print(item)
for file in cwd.glob('*.py'): # All Python files in current directory
print(file)
for excel in cwd.glob('*.xls'): # All Excel files in current directory
print(excel)
# List all items (files/folders) in directory
for child in cwd.iterdir():
print(child)
# Best Practice:
# Use pathlib # It's more readable and works the same on Windows, macOS etc
PYPI & PIP
PyPI and pip
PyPI: Python Package Index—central repository of published packages.
pip: Package installer for Python.
Common commands:
pip install package_name
pip install package_name==1.2.3
pip install -r requirements.txt
pip show package_name
pip uninstall package_name
Congratulations on completing Lesson 5!
You’ve now learned how to work with Python’s most important data structures, control the flow of your programs with loops and conditionals, and even read and write files. These skills form the foundation of almost every real-world Python script or project.
And with that, my “Basics of Python — Lesson Journey (Cheat Sheet Edition)” officially comes to an end. But don’t worry, the real adventure is just beginning! Up next, I’ll be diving into essential Python libraries, so make sure to follow and stick around for the next phase of this journey. Let’s keep leveling up together! 🚀
Subscribe to my newsletter
Read articles from Priyesh Shah directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Priyesh Shah
Priyesh Shah
Hi there👋 I'm Priyesh Shah 💻 B.Tech Computer Engineering student (2028) 🐍 Python, exploring AI/ML and open-source 🚀 Building projects to contribute to GSoC 2026