The Complete Python Guide
Basics to Advanced, Built-in Cheatsheet & IDEs
(Python 3)
A Practical Python Handbook
2026
Introduction
1. Getting Started
1.1 Installing Python 3
1.2 Your First Program
1.3 Comments
1.4 Variables and Assignment
1.5 Naming Rules
2. Core Data Types
2.1 Numbers
2.2 Strings
2.3 Booleans and None
2.4 Type Conversion
3. Collections
3.1 Lists — ordered, mutable
3.2 Tuples — ordered, immutable
3.3 Dictionaries — key/value pairs
3.4 Sets — unordered, unique elements
4. Control Flow
4.1 Conditionals
4.2 Loops
4.3 Comprehensions
5. Functions
5.1 Defining Functions
5.2 Default & Keyword Arguments
5.3 *args and **kwargs
5.4 Lambda Functions
5.5 Scope
6. Modules and Packages
7. Object-Oriented Programming (OOP)
7.1 Classes and Objects
7.2 Inheritance
7.3 Encapsulation
7.4 Polymorphism & Abstract Classes
7.5 Special (Dunder) Methods
8. Intermediate Concepts
8.1 Iterators and Generators
8.2 Decorators
8.3 Context Managers ( with )
8.4 Exception Handling
8.5 File Handling
9. Advanced Concepts
9.1 Type Hints
9.2 Concurrency
9.3 Metaclasses (advanced OOP)
9.4 Dataclasses
9.5 Unit Testing
9.6 Virtual Environments
10. Python Built-in Cheatsheet
10.1 String Methods
10.2 List Methods
10.3 Dictionary Methods
10.4 Tuple Methods
10.5 Set Methods
10.6 Common Built-in Functions
10.7 String Formatting Cheatsheet
11. Common Error Types (Quick Reference)
12. Python IDEs — PyCharm, Jupyter Notebook, Google Colab
12.1 PyCharm
12.2 Jupyter Notebook
12.3 Google Colab
12.4 Quick Comparison
Closing Notes
Introduction
This guide takes you from your first line of Python to advanced,
professional-level concepts. It is written for Python 3 — the current
and only actively developed version of the language (Python 2 reached
end-of-life in January 2020). Every example in this book uses correct,
runnable indentation (Python uses 4 spaces per indentation level by
convention — never mix tabs and spaces).
How this book is organized
1. Python fundamentals (variables, data types, control flow)
2. Functions, modules and packages
3. Object-Oriented Programming (OOP)
4. Intermediate concepts (comprehensions, generators, decorators,
context managers)
5. Advanced concepts (concurrency, metaclasses, typing, testing)
6. File handling, error handling and working with data
7. A complete Built-in Function & Data Structure Cheatsheet
8. Python IDEs — PyCharm, Jupyter Notebook, Google Colab
1. Getting Started
1.1 Installing Python 3
Download the latest Python 3 release from [Link]. On Windows,
tick “Add Python to PATH” during installation. Verify the install:
python3 --version
pip3 --version
1.2 Your First Program
# [Link]
print("Hello, World!")
Run it with:
python3 [Link]
1.3 Comments
# This is a single-line comment
"""
This is a multi-line string,
often used as a comment or docstring.
"""
1.4 Variables and Assignment
Python is dynamically typed — you don’t declare a type, Python
infers it.
name = "Alice" # str
age = 30 # int
height = 5.6 # float
is_student = False # bool
# Multiple assignment
x, y, z = 1, 2, 3
# Same value to multiple variables
a = b = c = 0
1.5 Naming Rules
Must start with a letter or underscore (not a digit)
Case-sensitive ( age and Age are different)
Cannot use reserved keywords ( if , for , class , etc.)
Convention: snake_case for variables/functions, PascalCase for
classes, UPPER_CASE for constants
2. Core Data Types
2.1 Numbers
integer_num = 10 # int
float_num = 10.5 # float
complex_num = 3 + 4j # complex
print(type(integer_num)) # <class 'int'>
# Arithmetic operators
print(10 + 3) # 13 addition
print(10 - 3) # 7 subtraction
print(10 * 3) # 30 multiplication
print(10 / 3) # 3.333... true division (always returns float)
print(10 // 3) # 3 floor division
print(10 % 3) # 1 modulus (remainder)
print(10 ** 3) # 1000 exponentiation
2.2 Strings
s = "Hello, Python!"
[Link]() # 'HELLO, PYTHON!'
[Link]() # 'hello, python!'
[Link]() # removes leading/trailing whitespace
[Link]("Python", "World") # 'Hello, World!'
[Link](",") # ['Hello', ' Python!']
len(s) # 15
s[0] # 'H' (indexing)
s[0:5] # 'Hello' (slicing)
s[::-1] # reversed string
f"Name: {s}" # f-string formatting
"-".join(["a", "b"]) # 'a-b'
2.3 Booleans and None
is_valid = True
result = None # represents "no value"
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool("text")) # True
2.4 Type Conversion
int("10") # 10
float("3.14") # 3.14
str(100) # '100'
list("abc") # ['a', 'b', 'c']
bool(1) # True
3. Collections
3.1 Lists — ordered, mutable
fruits = ["apple", "banana", "cherry"]
[Link]("date") # add to end
[Link](1, "mango") # insert at index
[Link]("banana") # remove by value
[Link]() # remove & return last item
[Link]() # sort in place
[Link]() # reverse in place
len(fruits) # length
"apple" in fruits # membership check
3.2 Tuples — ordered, immutable
point = (10, 20)
x, y = point # unpacking
[Link](10)
[Link](20)
3.3 Dictionaries — key/value pairs
person = {"name": "Alice", "age": 30}
person["email"] = "a@[Link]" # add/update
[Link]("age") # 30 (safe access)
[Link]() # dict_keys(['name', 'age', 'email'])
[Link]()
[Link]()
[Link]("age") # remove & return value
for k, v in [Link]():
print(k, v)
3.4 Sets — unordered, unique elements
a = {1, 2, 3}
b = {3, 4, 5}
[Link](4)
[Link](b) # {1,2,3,4,5}
[Link](b) # {3,4}
[Link](b) # {1,2}
4. Control Flow
4.1 Conditionals
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
# Ternary (conditional expression)
label = "Adult" if age >= 18 else "Minor"
4.2 Loops
# for loop
for fruit in ["apple", "banana"]:
print(fruit)
for i in range(5): # 0,1,2,3,4
print(i)
for i, fruit in enumerate(["apple", "banana"]):
print(i, fruit)
# while loop
count = 0
while count < 5:
print(count)
count += 1
# loop control
for i in range(10):
if i == 3:
continue # skip this iteration
if i == 7:
break # exit loop
print(i)
4.3 Comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
squared_dict = {x: x**2 for x in range(5)}
unique_set = {x % 3 for x in range(10)}
gen = (x**2 for x in range(10)) # generator expression (lazy)
5. Functions
5.1 Defining Functions
def greet(name):
"""Return a greeting for name."""
return f"Hello, {name}!"
print(greet("Alice"))
5.2 Default & Keyword Arguments
def power(base, exponent=2):
return base ** exponent
power(5) # 25 (uses default exponent)
power(5, 3) # 125
power(base=5, exponent=3) # keyword arguments
5.3 *args and **kwargs
def total(*args): # collects extra positional args into a tuple
return sum(args)
def describe(**kwargs): # collects extra keyword args into a dict
for key, value in [Link]():
print(f"{key}: {value}")
total(1, 2, 3) # 6
describe(name="Alice", age=30)
5.4 Lambda Functions
square = lambda x: x ** 2
add = lambda x, y: x + y
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
5.5 Scope
x = "global"
def outer():
x = "enclosing"
def inner():
nonlocal x
print(x)
inner()
def modify_global():
global x
x = "modified"
6. Modules and Packages
# math_utils.py
def add(a, b):
return a + b
# [Link]
import math_utils
math_utils.add(2, 3)
from math_utils import add
add(2, 3)
import math_utils as mu
[Link](2, 3)
# Standard library examples
import math
[Link](16) # 4.0
import random
[Link](1, 10)
import datetime
[Link]()
Packages are folders with an __init__.py file that group related
modules, imported using dotted paths, e.g. from [Link]
import function .
pip installs third-party packages:
pip install requests
pip freeze > [Link]
pip install -r [Link]
7. Object-Oriented Programming
(OOP)
7.1 Classes and Objects
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
[Link] = name # instance attribute
[Link] = age
def bark(self):
return f"{[Link]} says Woof!"
def __str__(self): # controls print(obj)
return f"Dog({[Link]}, {[Link]})"
d = Dog("Rex", 3)
print([Link]())
print(d)
7.2 Inheritance
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
raise NotImplementedError
class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"
class Puppy(Dog):
def bark(self):
return f"{[Link]} yips!" # method overriding
def bark_like_parent(self):
return super().bark() # call parent method
7.3 Encapsulation
class Account:
def __init__(self, balance):
self._balance = balance # protected (convention)
self.__pin = "1234" # private (name-mangled)
@property
def balance(self):
return self._balance
@[Link]
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = value
7.4 Polymorphism & Abstract Classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14159 * [Link] ** 2
for shape in [Circle(2), Circle(5)]:
print([Link]()) # polymorphism: same call, different behavior
7.5 Special (Dunder) Methods
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __len__(self):
return 2
def __repr__(self):
return f"Vector({self.x}, {self.y})"
8. Intermediate Concepts
8.1 Iterators and Generators
# Generator function — yields values lazily
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(5):
print(num)
# Manual iterator protocol
class Counter:
def __init__(self, limit):
[Link] = limit
self.n = 0
def __iter__(self):
return self
def __next__(self):
if self.n >= [Link]:
raise StopIteration
self.n += 1
return self.n
8.2 Decorators
import functools
import time
def timer(func):
@[Link](func)
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
print(f"{func.__name__} took {[Link]() - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
[Link](1)
# Decorator with arguments
def repeat(times):
def decorator(func):
@[Link](func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet():
print("Hi!")
8.3 Context Managers ( with )
with open("[Link]", "r") as f:
data = [Link]()
# file is automatically closed here
# Custom context manager
class Timer:
def __enter__(self):
[Link] = [Link]()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"Elapsed: {[Link]() - [Link]:.2f}s")
with Timer():
[Link](1)
# Using contextlib
from contextlib import contextmanager
@contextmanager
def open_resource():
print("Acquiring")
yield "resource"
print("Releasing")
8.4 Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type/Value error: {e}")
else:
print("Runs if no exception occurred")
finally:
print("Always runs (cleanup code)")
# Raising exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
# Custom exceptions
class InsufficientFundsError(Exception):
pass
8.5 File Handling
# Writing
with open("[Link]", "w") as f:
[Link]("Hello\n")
[Link](["Line1\n", "Line2\n"])
# Reading
with open("[Link]", "r") as f:
content = [Link]() # entire file as string
lines = [Link]() # list of lines
# Appending
with open("[Link]", "a") as f:
[Link]("New line\n")
# Working with JSON
import json
with open("[Link]", "w") as f:
[Link]({"name": "Alice"}, f)
with open("[Link]", "r") as f:
data = [Link](f)
# Working with CSV
import csv
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["name", "age"])
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row)
9. Advanced Concepts
9.1 Type Hints
def add(a: int, b: int) -> int:
return a + b
from typing import List, Dict, Optional, Union
def process(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
def find_user(id: int) -> Optional[str]:
return None
def parse(value: Union[int, str]) -> int:
return int(value)
9.2 Concurrency
# Threading — good for I/O-bound tasks
import threading
def worker(n):
print(f"Worker {n}")
threads = [[Link](target=worker, args=(i,)) for i in range(3)]
for t in threads: [Link]()
for t in threads: [Link]()
# Multiprocessing — good for CPU-bound tasks
from multiprocessing import Pool
def square(x):
return x * x
with Pool(4) as p:
print([Link](square, [1, 2, 3, 4]))
# Async/await — cooperative concurrency
import asyncio
async def fetch_data():
await [Link](1)
return "data"
async def main():
result = await fetch_data()
print(result)
[Link](main())
9.3 Metaclasses (advanced OOP)
class Meta(type):
def __new__(mcs, name, bases, namespace):
namespace['created_by'] = 'Meta'
return super().__new__(mcs, name, bases, namespace)
class MyClass(metaclass=Meta):
pass
print(MyClass.created_by) # 'Meta'
9.4 Dataclasses
from dataclasses import dataclass, field
@dataclass
class Point:
x: int
y: int
tags: list = field(default_factory=list)
p = Point(1, 2) # __init__, __repr__, __eq__ generated automatically
9.5 Unit Testing
import unittest
def add(a, b):
return a + b
class TestMath([Link]):
def test_add(self):
[Link](add(2, 3), 5)
if __name__ == "__main__":
[Link]()
# pytest style (simpler, widely used)
def test_add():
assert add(2, 3) == 5
9.6 Virtual Environments
python3 -m venv venv # create
source venv/bin/activate # activate (Linux/Mac)
venv\Scripts\activate # activate (Windows)
deactivate # exit
10. Python Built-in Cheatsheet
This section lists the most-used methods for each core built-in type,
what they do, and their format. s = string, L = list, d = dict, t =
tuple, st = set.
10.1 String Methods
Method Format Description
upper() [Link]() Returns a copy in all
uppercase
lower() [Link]() Returns a copy in all
lowercase
title() [Link]() Capitalizes the first letter of
each word
capitalize() [Link]() Capitalizes only the first
character
strip() [Link](chars=None) Removes leading/trailing
whitespace (or given chars)
lstrip()/rstrip() [Link]() Strips from left/right only
replace() [Link](old, new) Replaces all occurrences of
old with new
split() [Link](sep=None) Splits into a list on sep
(default: whitespace)
rsplit() [Link](sep, maxsplit) Splits from the right
splitlines() [Link]() Splits at line boundaries
join() [Link](iterable) Joins iterable items with sep
between them
find() [Link](sub) Returns lowest index of sub ,
or -1 if not found
index() [Link](sub) Like find() , but raises
ValueError if missing
count() [Link](sub) Counts non-overlapping
occurrences of sub
startswith() [Link](prefix) True if string starts with
prefix
endswith() [Link](suffix) True if string ends with
suffix
format() [Link](*args) Substitutes {} placeholders
zfill() [Link](width) Pads string with zeros on the
left
isalpha()/isdigit()/isalnum() [Link]() Checks character class of the
whole string
isupper()/islower() [Link]() Checks case of the whole
string
swapcase() [Link]() Swaps upper/lowercase
center()/ljust()/rjust() [Link](width) Pads/aligns string to a width
encode() [Link](encoding) Converts string to bytes
format_map() s.format_map(d) Formats using a
mapping/dict
10.2 List Methods
Method Format Description
append() [Link](x) Adds x to the end of the list
extend() [Link](iterable) Appends all items from
another iterable
insert() [Link](i, x) Inserts x at index i
remove() [Link](x) Removes first item equal to
x (raises if absent)
pop() [Link](i=-1) Removes & returns item at
index i (default: last)
clear() [Link]() Removes all items
index() [Link](x) Returns index of first item
equal to x
count() [Link](x) Counts occurrences of x
sort() [Link](key=None, Sorts the list in place
reverse=False)
reverse() [Link]() Reverses the list in place
copy() [Link]() Returns a shallow copy
sorted() (built-in) sorted(L) Returns a new sorted list
(original unchanged)
len() (built-in) len(L) Returns number of items
slicing L[start:stop:step] Returns a sub-list
list comprehension [x for x in L if cond] Builds a new list
10.3 Dictionary Methods
Method Format Description
get() [Link](key, default=None) Returns value for key , or
default if missing
keys() [Link]() Returns view of all keys
values() [Link]() Returns view of all values
items() [Link]() Returns view of (key, value)
pairs
update() [Link](other) Merges another dict/iterable
of pairs into d
pop() [Link](key, default) Removes key and returns its
value
popitem() [Link]() Removes & returns the last
inserted (key, value)
setdefault() [Link](key, default) Returns value if key exists,
else sets & returns default
clear() [Link]() Removes all items
copy() [Link]() Returns a shallow copy
fromkeys() [Link](seq, value) Creates a dict from a
sequence of keys
dict comprehension {k: v for k, v in [Link]()} Builds a new dict
10.4 Tuple Methods
Method Format Description
count() [Link](x) Counts occurrences of x
index() [Link](x) Returns index of first
occurrence of x
unpacking a, b = t Assigns tuple elements to
variables
zip() (built-in) zip(t1, t2) Pairs elements from multiple
iterables
10.5 Set Methods
Method Format Description
add() [Link](x) Adds element x
remove() [Link](x) Removes x (raises KeyError
if absent)
discard() [Link](x) Removes x if present (no
error if absent)
union() [Link](other) or st \| Returns combined set of both
other
intersection() [Link](other) or st Returns common elements
& other
difference() [Link](other) or st - Returns elements only in st
other
symmetric_difference() st ^ other Returns elements in either,
not both
issubset() [Link](other) True if st is contained in
other
issuperset() [Link](other) True if st contains other
pop() [Link]() Removes & returns an
arbitrary element
clear() [Link]() Removes all elements
10.6 Common Built-in Functions
Function Format Description
print() print(*values, sep=' ', Prints to stdout
end='\n')
len() len(obj) Length of a collection/string
range() range(start, stop, step) Generates a sequence of
numbers
enumerate() enumerate(iterable, start=0) Pairs items with their index
zip() zip(*iterables) Combines multiple iterables
element-wise
map() map(func, iterable) Applies func to every item
filter() filter(func, iterable) Keeps items where
func(item) is True
sorted() sorted(iterable, key=None, Returns a new sorted list
reverse=False)
reversed() reversed(seq) Returns a reverse iterator
sum() sum(iterable, start=0) Sums numeric items
min()/max() min(iterable) Smallest/largest item
abs() abs(x) Absolute value
round() round(x, ndigits=0) Rounds a number
type() type(obj) Returns the object’s type
isinstance() isinstance(obj, cls) Checks if object is instance of
a class
input() input(prompt) Reads a line of user input as
a string
open() open(path, mode) Opens a file, returns a file
object
id() id(obj) Returns the object’s unique
memory identity
all() all(iterable) True if every item is truthy
any() any(iterable) True if at least one item is
truthy
dir() dir(obj) Lists an object’s
attributes/methods
help() help(obj) Displays documentation
10.7 String Formatting Cheatsheet
name, age = "Alice", 30
# f-strings (preferred, Python 3.6+)
f"{name} is {age} years old"
f"{3.14159:.2f}" # '3.14' (2 decimal places)
f"{1000000:,}" # '1,000,000'
f"{5:04d}" # '0005'
# .format() method
"{} is {}".format(name, age)
"{0} is {1}, {0} again".format(name, age)
# % operator (legacy)
"%s is %d" % (name, age)
11. Common Error Types (Quick
Reference)
Exception When it occurs
SyntaxError Invalid Python syntax
NameError Using a variable that doesn’t exist
TypeError Operation applied to an incompatible type
ValueError Correct type but inappropriate value
IndexError List/tuple index out of range
KeyError Dictionary key not found
AttributeError Object has no such attribute/method
ZeroDivisionError Division by zero
FileNotFoundError File does not exist
ImportError/ModuleNotFoundError Module cannot be found/imported
IndentationError Incorrect indentation
StopIteration Iterator has no more items
12. Python IDEs — PyCharm,
Jupyter Notebook, Google Colab
12.1 PyCharm
PyCharm (by JetBrains) is a full-featured IDE for serious Python
projects.
Setup
1. Download PyCharm Community (free) or Professional from
[Link].
2. Install and open it, then File > New Project.
3. Choose a location and let PyCharm create a virtual environment
automatically.
Key features
Intelligent code completion and real-time error checking
Integrated debugger — set breakpoints by clicking the gutter,
then run in Debug mode (Shift+F9) to step through code, inspect
variables
Integrated terminal ( Alt+F12 ) and built-in Git support
Refactoring tools — rename a variable everywhere with Shift+F6
Virtual environment management under Settings > Project >
Python Interpreter
Run configurations to run scripts with specific arguments/env
variables
Best for: large applications, web backends (Django/Flask), teams
needing strong refactoring and debugging tools.
12.2 Jupyter Notebook
Jupyter runs Python in cells you execute independently — ideal for
data exploration, learning, and step-by-step experimentation.
Setup
pip install notebook
jupyter notebook
This opens a browser tab at localhost:8888 . Create a new notebook
( .ipynb ) and select the Python 3 kernel.
Working with cells
Shift+Enter — run the current cell and move to the next
Ctrl+Enter — run the current cell and stay
Esc then A / B — insert a cell above/below
Esc then M — convert a cell to Markdown (for notes/headings)
Esc then D , D — delete a cell
# Cell 1
import pandas as pd
df = pd.read_csv("[Link]")
# Cell 2 — variables persist between cells
[Link]()
Magic commands
%timeit sum(range(1000)) # times execution
%matplotlib inline # display plots inline
!pip install numpy # run shell commands
Best for: data analysis, visualization, machine learning,
teaching/tutorials.
12.3 Google Colab
Colab is a free, cloud-hosted Jupyter Notebook environment — no
installation required, and it includes free GPU/TPU access.
Setup
1. Go to [Link] and sign in with a Google
account.
2. File > New Notebook.
3. Cells work exactly like Jupyter ( Shift+Enter to run).
Key features
Runs entirely in the browser — files are saved to Google Drive
Free GPU/TPU: Runtime > Change runtime type > Hardware
accelerator
Install packages per-session: !pip install package_name
Mount Google Drive for persistent file storage:
from [Link] import drive
[Link]('/content/drive')
Easy sharing — share a Colab notebook link like a Google Doc
Best for: machine learning experiments, GPU-heavy work, sharing
runnable notebooks without asking collaborators to install anything.
12.4 Quick Comparison
Tool Setup Best use case Cost
PyCharm Local install Full applications, Free (Community) /
debugging, Paid
refactoring
Jupyter Notebook Local install ( pip ) Data exploration, Free
teaching
Google Colab None (browser) ML with free GPU, Free (paid tiers
collaboration optional)
Closing Notes
You now have a complete map of Python 3 from fundamentals through
advanced topics, a built-in function/method cheatsheet you can use as
a daily reference, and a guide to the three most common tools for
writing and running Python. The companion guide continues with
practical, applied Python: automation, game development, web
scraping, data science libraries, GUI development, and a full Streamlit
tutorial.