Dive into Python programming basics, including syntax, data
structures, and scripting for automation or backend tasks.
Python is a high‑level, interpreted, general‑purpose programming language known for its readability and vast standard library.
# hello.py
print("Hello, Python!")
Download from python.org
or install via package manager.
Use python -m venv venv
to create isolated environments.
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
The Read‑Eval‑Print‑Loop lets you test snippets quickly.
$ python
>>> 2 + 3
5
Dynamic typing—no need to declare types explicitly (int, float, str, bool, list, tuple, dict, set).
x = 10 # int
pi = 3.14 # float
name = "Alice" # str
input()
reads user input; print()
writes to
stdout.
name = input("Your name: ")
print("Hi", name)
+ - * / // % **
perform maths; //
is
floor‑division, **
exponentiation.
area = 0.5 * base * height
Use upper()
, replace()
, slicing, and
f‑strings for formatting.
msg = f"{name.upper()} scored {marks}/100"
if elif else
control flow.
if temp > 40:
print("Hot")
elif temp > 20:
print("Warm")
else:
print("Cold")
for
iterates over sequences; while
repeats
until condition false.
for i in range(1, 6):
print(i**2)
Concise way to build lists from iterables.
squares = [i*i for i in range(10) if i % 2 == 0]
Immutable ordered collections; convenient for returning multiple values.
point = (3, 4)
x, y = point
Key‑value mapping; constant‑time lookup.
student = {"id": 101, "name": "Ana", "cgpa": 8.9}
for k, v in student.items():
print(k, v)
Unordered collection of unique items; supports union, intersection.
odd = {1, 3, 5}; even = {2, 4, 6}
print(odd | even)
Reusable blocks; document with triple‑quoted strings.
def add(a, b):
"""Return sum of a and b."""
return a + b
Anonymous functions combined with functional helpers.
doubles = list(map(lambda x: 2*x, [1,2,3]))
evens = list(filter(lambda x: x%2==0, range(10)))
Gracefully catch runtime errors using
try‑except‑else‑finally
.
try:
ans = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero.")
finally:
print("Done")
Read & write files with context managers to ensure proper closing.
with open("data.txt") as f:
lines = f.readlines()
Organise code into separate files; import with
import mod
or from mod import func
.
# utils.py
def greet():
print("Hi")
# main.py
import utils
utils.greet()
Manage dependencies; pip install requests
installs
packages from PyPI.
pip freeze > requirements.txt
Classes encapsulate data and behaviour; supports inheritance and polymorphism.
class Vehicle:
def __init__(self, name): self.name = name
def move(self): print(self.name, "moves")
class Car(Vehicle): pass
Car("Tesla").move()
Control attribute access while keeping dot syntax.
class Circle:
def __init__(self, r): self._r = r
@property
def area(self): return 3.14 * self._r**2
Lazy iterables that save memory.
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a+b
Functions that modify behaviour of other functions.
def timer(fn):
import time
def wrap(*a, **kw):
s = time.time(); result = fn(*a, **kw);
print("took", time.time()-s); return
result
return wrap
Automate setup/teardown by defining
__enter__
/__exit__
.
from contextlib import contextmanager
@contextmanager
def open_db():
print("connect"); yield; print("close")
Powerful pattern matching and text processing.
import re
emails = re.findall(r"[a-zA-Z0-9._%+-]+@[\w.-]+", text)
Convert between Python objects and JSON strings with
json
module.
import json
data = json.loads('{"x":1}')
print(json.dumps(data, indent=2))
Send/receive web data easily (third‑party library).
import requests
r = requests.get("https://api.github.com")
print(r.status_code)
threading
for I/O‑bound; multiprocessing
for
CPU‑bound tasks.
from multiprocessing import Pool
print(Pool().map(lambda x: x*x, range(5)))
Handle thousands of concurrent I/O operations using
async def
and await
.
import asyncio, aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as s:
async with s.get(url) as r: return await
r.text()
Task: Write a program that solves ax² + bx + c = 0
for
real/complex roots.
import cmath
a,b,c = 1, -3, 2
d = cmath.sqrt(b*b - 4*a*c)
root1 = (-b + d)/(2*a)
root2 = (-b - d)/(2*a)
print(root1, root2)
Combines multiple iterables into tuples, pairing elements by position.
names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
print(name, "scored", score)
Adds a counter while iterating over an iterable.
colors = ['Red', 'Green', 'Blue']
for index, color in enumerate(colors):
print(index, color)
Check object type at runtime for type-safe code.
x = 5
print(isinstance(x, int))
print(type(x) == int)
Used to pass command-line arguments to a script.
import sys
print("Arguments:", sys.argv)
Provides access to the operating system (file paths, directories, etc.).
import os
print("Current Dir:", os.getcwd())
os.mkdir("new_folder")
Used for high-level file operations like copy, move, delete.
import shutil
shutil.copy("file1.txt", "file2.txt")
Used to work with date and time objects.
from datetime import datetime
now = datetime.now()
print(now.strftime("%d-%m-%Y %H:%M:%S"))
Provides functions to track and manipulate time (e.g., sleep).
import time
print("Wait 2 seconds...")
time.sleep(2)
print("Done")
Standard math library for advanced calculations.
import math
print(math.sqrt(16))
print(math.factorial(5))
Provides basic statistical functions like mean, median, mode.
import statistics
data = [10, 20, 30]
print("Mean:", statistics.mean(data))
Generates pseudo-random numbers and choices.
import random
print(random.randint(1, 10))
print(random.choice(["red", "green", "blue"]))
Offers fast, memory-efficient tools for iterators (combinations, permutations).
from itertools import permutations
for p in permutations([1, 2, 3]):
print(p)
Used to test if a condition is true; helps in debugging.
x = 10
assert x > 0, "x must be positive"
Framework for writing and running tests for your code.
import unittest
class TestSum(unittest.TestCase):
def test_add(self): self.assertEqual(1+2, 3)
Tests embedded in docstrings using example-based testing.
def add(a, b):
"""Returns sum
>>> add(2, 3)
5
"""
return a + b
Provides a flexible system for logging messages.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is info")
Gracefully exits the program with an optional status code.
import sys
if error: sys.exit("Exiting due to error.")
Checks whether script is being run directly or imported.
if __name__ == "__main__":
main()
Read and write CSV (Comma Separated Values) files.
import csv
with open('data.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
Serialize and deserialize Python objects to store them in files.
import pickle
with open("obj.pkl", "wb") as f:
pickle.dump({"a": 1}, f)
NumPy provides high-performance multi-dimensional arrays and numerical operations.
import numpy as np
a = np.array([1, 2, 3])
print(a * 2)
Allows accessing subarrays using indices and ranges.
a = np.array([1,2,3,4,5])
print(a[1:4])
DataFrame is a 2D tabular data structure with labeled axes (rows & columns).
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Score': [90, 80]})
print(df)
One-dimensional labeled array capable of holding any data type.
s = pd.Series([1, 3, 5])
print(s)
Apply conditions to filter rows in DataFrames.
print(df[df['Score'] > 85])
Matplotlib is used to generate plots, charts, and visualizations.
import matplotlib.pyplot as plt
plt.plot([1,2,3], [4,5,6])
plt.show()
SQLite is a lightweight SQL database embedded into Python via the sqlite3 module.
import sqlite3
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS student (id INT, name
TEXT)")
conn.commit()
Tkinter is the standard GUI toolkit for Python to build desktop apps.
from tkinter import *
root = Tk()
Label(root, text="Hello GUI").pack()
root.mainloop()
BeautifulSoup is used to extract data from HTML and XML documents.
from bs4 import BeautifulSoup
soup =
BeautifulSoup("<html><h1>Hello</h1></html>",
'html.parser')
print(soup.h1.text)
Flask is a lightweight web framework for building web apps and APIs.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home(): return "Hello Flask"
Define routes using decorators that match URLs to functions.
@app.route("/user/<name>")
def greet(name): return f"Hello {name}"
Django is a high-level Python web framework for rapid development and clean design.
# In views.py
from django.http import HttpResponse
def index(request): return HttpResponse("Welcome to Django")
Django models define the structure of database tables.
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=50)
Auto-generated interface for managing models.
# In admin.py
from .models import Student
admin.site.register(Student)
Python’s built-in SMTP library for sending emails through code.
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
CSV files can be processed with the built-in csv module or Pandas.
import csv
with open('data.csv') as f:
reader = csv.reader(f)
for row in reader: print(row)
JSON is widely used for config files and API responses.
import json
data = {"name": "John"}
with open("data.json", "w") as f:
json.dump(data, f)
Used to perform multiple I/O operations simultaneously in a single process.
import threading
def task(): print("Running thread")
threading.Thread(target=task).start()
Used for parallel CPU-bound processing across multiple processes.
from multiprocessing import Process
def job(): print("Child Process")
p = Process(target=job)
p.start(); p.join()
Introduced in Python 3.7, dataclasses simplify class creation for data storage.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
Creates isolated environments for different projects to manage dependencies separately.
python -m venv myenv
source myenv/bin/activate (Linux/Mac)
myenv\Scripts\activate (Windows)
Functions that modify the behavior of other functions using
@
syntax.
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def greet(): print("Hello")
greet()
Generators use yield
to produce a sequence of values
lazily (on demand).
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(3): print(i)
Defines how to access items in a container using
__iter__()
and __next__()
.
class Counter:
def __init__(self): self.count = 0
def __iter__(self): return self
def __next__(self):
if self.count < 3:
self.count += 1
return self.count
else: raise StopIteration
for i in Counter(): print(i)
Small anonymous functions using lambda
keyword.
square = lambda x: x * x
print(square(5))
Functional programming tools for applying functions to iterables.
from functools import reduce
nums = [1,2,3,4]
print(list(map(lambda x: x*2, nums)))
print(list(filter(lambda x: x%2==0, nums)))
print(reduce(lambda x,y: x+y, nums))
Create distributable Python packages using setuptools
.
from setuptools import setup
setup(name='mypackage', version='1.0', py_modules=['mymodule'])
pip
is used to install packages from the Python Package
Index (PyPI).
pip install numpy
pip uninstall requests
Binary distribution format for faster installation of Python packages.
pip install mypackage.whl
Bundles Python apps into standalone executables.
pip install pyinstaller
pyinstaller myscript.py
Used to create command-line tools with argument parsing.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
print(args.name)
Read/write JSON data using the built-in json
module.
import json
data = {"a": 10}
json_str = json.dumps(data)
print(json.loads(json_str))
Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
import logging
logging.basicConfig(level=logging.WARNING)
logging.warning("This is a warning")
Auto-discover test files using unittest framework.
python -m unittest discover
Used to manage resources like files, automatically closes them.
with open("file.txt") as f:
data = f.read()
Marks a directory as a Python package; can include initialization code.
# __init__.py
print("Initializing package")
Interactive coding environment, great for data science and teaching.
pip install notebook
jupyter notebook
Special methods like __str__
, __add__
, etc.,
that add functionality to classes.
class Person:
def __str__(self): return "This is a Person"
Optional type annotations to improve code clarity and tooling.
def greet(name: str) -> str:
return "Hi " + name
Lists all dependencies of a project; used by pip to install them.
# requirements.txt
numpy==1.21.0
pandas==1.3.0
pip install -r requirements.txt
Used to limit the attributes an object can have, reducing memory usage.
class Person:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
Provides controlled access to class attributes via getter/setter methods.
class Circle:
def __init__(self, radius): self._radius = radius
@property
def radius(self): return self._radius
Advanced feature to customize attribute access using
__get__
, __set__
.
class Descriptor:
def __get__(self, obj, type=None): return "Got it"
class Demo:
x = Descriptor()
print(Demo().x)
Stores an object’s attributes in a dictionary format.
class Car:
def __init__(self): self.color = "red"
print(Car().__dict__)
__str__
is used for user-friendly string,
__repr__
for developer/debugging.
class Data:
def __str__(self): return "User View"
def __repr__(self): return "Developer View"
Automatically reclaims unused memory by deleting unreachable objects.
import gc
gc.collect() # Manually trigger garbage collection
Used to create weak references to objects, avoiding memory leaks in caches.
import weakref
class MyClass: pass
obj = MyClass()
r = weakref.ref(obj)
print(r())
Used to access the internal data of an object without copying.
data = bytearray(b'abc')
mv = memoryview(data)
print(mv[0]) # ASCII of 'a'
Helps create context managers (like with statements) easily.
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name)
yield f
f.close()
Supports asynchronous programming for handling I/O-bound tasks efficiently.
import asyncio
async def main():
print("Waiting...")
await asyncio.sleep(1)
print("Done")
asyncio.run(main())
📘 Official Python Docs: https://docs.python.org/3/
🐍 W3Schools Python: https://www.w3schools.com/python/
🎓 GeeksforGeeks Python: https://www.geeksforgeeks.org/python-programming-language/
💡 Real Python Tutorials: https://realpython.com/
📒 Jupyter Notebooks: https://jupyter.org/
📦 PyPI (Package Index): https://pypi.org/