Python Cheat Sheet – Complete Python Syntax & Commands Reference

Python Beginner Friendly Free PDF Soon

Python Cheat Sheet

A complete Python syntax and commands reference for beginners and intermediate developers. Quickly find the Python examples you need for variables, data types, strings, lists, loops, functions, files, exceptions and more.

Last updated: July 2026 Examples: 100+ Tables: 25+
QUICK REFERENCE

Python Quick Reference

Quickly find the most commonly used Python syntax, functions and language features. This quick reference is designed for everyday coding and fast lookup.

Basic Syntax

These are the core Python syntax elements you will use constantly when writing, testing and understanding Python code.

Syntax Description Example Copy
print() Print output to the console. print("Hello, World!")
# Create a single-line comment. # This is a comment
""" """ Create a multi-line string. """Multi-line text"""
= Assign a value to a variable. x = 10
type() Return the type of an object. type(x)
help() Show documentation for an object. help(str)
dir() List available attributes and methods. dir(list)
Pro Tip: Use help() when you want documentation and dir() when you want to inspect available methods and attributes.

Variables

Variables are used to store data in Python. Unlike many other programming languages, Python variables are dynamically typed, meaning you don’t need to declare a data type before assigning a value.

Syntax Description Example Copy
x = 10 Create an integer variable. x = 10
name = "Alice" Create a string variable. name = "Alice"
price = 19.99 Create a floating-point variable. price = 19.99
is_admin = True Create a boolean variable. is_admin = True
a, b = 1, 2 Assign multiple variables at once. a, b = 1, 2
x += 1 Increase a variable value. x += 1
PI = 3.14159 Constant naming convention. PI = 3.14159
del x Delete a variable. del x
Pro Tip: Use descriptive variable names like total_price or customer_name instead of single letters. It makes your code much easier to read and maintain.

Data Types

Python includes several built-in data types for storing different kinds of information. Choosing the right data type makes your code more efficient, readable and easier to maintain.

Data Type Description Example Copy
int Whole numbers. x = 42
float Decimal numbers. price = 19.99
str Text values. name = 'Alice'
bool Boolean values. is_admin = True
list Ordered, mutable collection. numbers = [1,2,3]
tuple Ordered, immutable collection. point = (10,20)
set Unordered collection of unique values. colors = {'red','blue'}
dict Key-value pairs. user = {'name':'Alice'}
NoneType Represents no value. result = None

Quick Comparison

Compare Python’s most common collection data types at a glance.

Data Type Ordered Mutable Allows Duplicates Typical Use
list Dynamic collections
tuple Fixed data
set Unique values
dict ✅* Keys ❌
Values ✅
Fast key-value lookup

* Dictionaries preserve insertion order in Python 3.7 and later.

Pro Tip: Use list when the data can change, tuple for fixed values, set for unique items, and dict when you need fast key-value lookups.

Operators

Python operators are used to perform calculations, compare values, assign data and combine logical conditions. They are essential for writing expressions and controlling program logic.

Operator Description Example Copy
+ Add values. x + y
- Subtract values. x - y
* Multiply values. x * y
/ Divide values and return a float. x / y
// Floor division. x // y
% Return the remainder. x % y
** Exponentiation. x ** 2
== Equal to. x == y
!= Not equal to. x != y
> Greater than. x > y
>= Greater than or equal to. x >= y
and Return true if both conditions are true. x > 0 and y > 0
in Check if a value exists in a sequence. "a" in text
is Check if two variables reference the same object. x is None

Common Operator Groups

Use this table to quickly understand which type of operator you need.

Group Operators Used For
Arithmetic + - * / // % ** Math calculations
Comparison == != > < >= <= Comparing values
Logical and or not Combining conditions
Membership in, not in Checking if a value exists
Identity is, is not Checking object identity
Common Mistake: Use == to compare values and is to compare object identity. For example, use x == 5 for value comparison and x is None when checking for None.

Input & Output

Python makes it easy to interact with users and display information. Use input() to read user input and print() to display output in the console.

Function Description Example Copy
print() Display output. print("Hello")
input() Read user input. name = input("Name: ")
sep= Change the separator between printed values. print(a, b, sep=", ")
end= Change the line ending. print("Hello", end="")
f-string Embed variables inside strings. print(f"Hello {name}")
format() Format strings using placeholders. "Hello {}".format(name)
int(input()) Read an integer. age = int(input())
float(input()) Read a decimal number. price = float(input())

Input Conversion

The input() function always returns a string. Convert it to another type when needed.

Input Returns Example
input() String name = input()
int(input()) Integer age = int(input())
float(input()) Float price = float(input())
bool(input()) Boolean* flag = bool(input())

* bool(input()) returns True for any non-empty string. It does not convert text like "True" or "False" into boolean values.

Pro Tip: Use f-strings whenever possible. They are easier to read, faster than older formatting methods, and are the recommended approach in modern Python.

Strings

Strings are one of the most commonly used data types in Python. They provide many built-in methods for searching, formatting, modifying and manipulating text.

Method Description Example Copy
len() Return string length. len(text)
upper() Convert to uppercase. text.upper()
lower() Convert to lowercase. text.lower()
title() Capitalize every word. text.title()
capitalize() Capitalize first letter. text.capitalize()
strip() Remove leading and trailing spaces. text.strip()
replace() Replace text. text.replace("a","b")
split() Split a string into a list. text.split(",")
join() Join iterable into a string. ", ".join(items)
find() Find the first occurrence. text.find("cat")
count() Count occurrences. text.count("a")
startswith() Check string prefix. text.startswith("Mr")
endswith() Check string suffix. text.endswith(".txt")
f-string Modern string formatting. f"Hello {name}"

Common String Operations

The table below shows the most common tasks you’ll perform when working with strings.

Task Recommended Method
Convert to uppercase upper()
Convert to lowercase lower()
Remove whitespace strip()
Replace text replace()
Split text split()
Join strings join()
Search text find()
Count characters count()
String formatting f-strings
Pro Tip: Use f-strings for string formatting whenever possible. They are cleaner, easier to read, and generally faster than older formatting techniques like format() or the % operator.

Lists

Lists are ordered, mutable collections that can store items of different data types. They are one of the most frequently used data structures in Python and are ideal for storing and manipulating sequences of data.

Method Description Example Copy
append() Add an item to the end. items.append("apple")
extend() Add multiple items. items.extend(other)
insert() Insert at a specific index. items.insert(0,"apple")
remove() Remove by value. items.remove("apple")
pop() Remove by index and return the value. items.pop()
clear() Remove all items. items.clear()
sort() Sort the list. items.sort()
reverse() Reverse the order. items.reverse()
copy() Create a shallow copy. new_list = items.copy()
len() Return the number of items. len(items)
in Check if a value exists. "apple" in items
count() Count matching items. items.count("apple")
index() Find item index. items.index("apple")
sorted() Return a sorted copy. sorted(items)

Common List Operations

These are the most common tasks you’ll perform when working with Python lists.

Task Recommended Method
Add one item append()
Add multiple items extend()
Insert at position insert()
Delete by value remove()
Delete by index pop()
Sort list sort()
Reverse order reverse()
Create sorted copy sorted()
Check existence in
Find position index()
Pro Tip: Use sorted(list) when you need a sorted copy and list.sort() when you want to sort the original list in place.

Tuples

Tuples are ordered, immutable collections. Use tuples when you want to store values that should not change, such as coordinates, fixed settings or grouped return values.

Syntax Description Example Copy
() Create an empty tuple. items = ()
(1, 2, 3) Create a tuple. numbers = (1, 2, 3)
("apple",) Create a single-item tuple. item = ("apple",)
tuple() Convert iterable to tuple. items = tuple([1, 2, 3])
len() Return tuple length. len(items)
count() Count matching values. items.count("apple")
index() Find value index. items.index("apple")
in Check if value exists. "apple" in items
a, b = pair Unpack tuple values. x, y = point
Common Mistake: A single-item tuple needs a trailing comma. Use ("apple",), not ("apple"). Without the comma, Python treats it as a normal string expression.

Sets

Sets are unordered collections of unique values. They automatically remove duplicates and are commonly used for membership testing, eliminating duplicate items and performing mathematical set operations.

Method Description Example Copy
set() Create an empty set. items = set()
{1,2,3} Create a set with values. numbers = {1,2,3}
add() Add one value. items.add("apple")
update() Add multiple values. items.update(other)
remove() Remove a value. items.remove("apple")
discard() Remove a value safely. items.discard("apple")
pop() Remove a random item. items.pop()
clear() Remove all values. items.clear()
union() Combine two sets. a.union(b)
intersection() Find common values. a.intersection(b)
difference() Find unique values. a.difference(b)
issubset() Check subset. a.issubset(b)
in Check membership. "apple" in items

Common Set Operations

Python sets are optimized for working with unique values and mathematical set operations.

Task Recommended Method
Add one value add()
Add multiple values update()
Remove value remove()
Remove safely discard()
Merge sets union()
Find common values intersection()
Find differences difference()
Membership test in
Pro Tip: Sets automatically remove duplicate values and provide very fast membership testing. Use a set instead of a list when checking whether a value exists frequently.

Dictionaries

Dictionaries store data as key-value pairs. They are ordered, mutable and optimized for fast lookups, making them one of the most powerful and frequently used data structures in Python.

Method / Syntax Description Example Copy
{} Create an empty dictionary. user = {}
dict() Create a dictionary. user = dict()
dict[key] Access a value. user["name"]
get() Safely retrieve a value. user.get("name")
keys() Return all keys. user.keys()
values() Return all values. user.values()
items() Return key-value pairs. user.items()
update() Update or merge dictionaries. user.update(data)
pop() Remove a key. user.pop("age")
popitem() Remove the last inserted item. user.popitem()
clear() Remove all items. user.clear()
copy() Create a shallow copy. new_user = user.copy()
setdefault() Return a value or create it if missing. user.setdefault("age", 18)
in Check if a key exists. "name" in user

Common Dictionary Operations

These are the most common tasks you’ll perform when working with dictionaries.

Task Recommended Method
Create dictionary {} or dict()
Read a value dict[key]
Safe lookup get()
Add or update dict[key] = value
Merge dictionaries update()
Remove key pop()
Loop through keys keys()
Loop through values values()
Loop through key-value pairs items()
Check if key exists in
Pro Tip: Use dict.get("key") instead of dict["key"] when a key might not exist. The get() method returns None (or a default value you specify) instead of raising a KeyError.
Common Mistake: The in operator checks keys, not values.

"name" in user
"Antonio" in user

Conditionals

Conditional statements control the flow of a Python program by executing different blocks of code depending on whether a condition evaluates to True or False.

Keyword Description Example Copy
if Execute code if a condition is true. if age >= 18:
match Pattern matching (Python 3.10+). match command:
case Define a match branch. case "start":
pass Placeholder statement. pass
and Both conditions must be true. age > 18 and active
not Invert a condition. not active

Conditional Flow

Python evaluates conditional statements from top to bottom and executes the first matching branch.

Structure Purpose
if Run code when a condition is true.
if / else Choose between two outcomes.
if / elif / else Handle multiple conditions.
match / case Pattern matching for multiple values.
Pro Tip: Keep conditions simple and readable. If a condition becomes long, assign parts of it to descriptive variables before using them in an if statement.
Common Mistake: Remember to use a colon (:) after if, elif, else, match and case. Python will raise a SyntaxError if the colon is missing.

Loops

Loops allow you to execute the same block of code multiple times. Python supports for loops for iterating over sequences and while loops for repeating code while a condition is true.

Keyword / Function Description Example Copy
for Loop over an iterable. for item in items:
while Loop while a condition is true. while x < 10:
range() Generate a sequence of numbers. range(5)
enumerate() Get index and value. enumerate(items)
zip() Iterate over multiple iterables. zip(a, b)
break Exit the loop immediately. break
continue Skip the current iteration. continue
pass Placeholder statement. pass
else Run after a loop finishes normally. for x in nums: ... else:
reversed() Iterate in reverse order. reversed(items)
sorted() Loop over sorted data. sorted(items)

Choosing the Right Loop

Choose the loop that best matches the task you’re trying to solve.

Task Recommended
Loop through a list for
Repeat until a condition changes while
Need the current index enumerate()
Loop over two lists together zip()
Loop a fixed number of times range()
Exit early break
Skip one iteration continue
Reverse iteration reversed()
Pro Tip: Use enumerate() instead of manually incrementing a counter. It’s cleaner, more Pythonic, and less error-prone.
Common Mistake: Avoid modifying a list while iterating over it. If you need to change the contents, iterate over a copy using items.copy() or create a new list instead.

Functions

Functions let you organize reusable code into named blocks. They improve readability, reduce duplication, and make programs easier to test and maintain.

Syntax Description Example Copy
def Define a function. def greet():
return Return a value. return result
Parameters Pass values into a function. def add(a, b):
Default Value Provide a default argument. def greet(name='Guest'):
*args Accept multiple positional arguments. def total(*args):
**kwargs Accept keyword arguments. def user(**kwargs):
lambda Create an anonymous function. lambda x: x * 2
Type Hints Specify expected types. def add(a:int,b:int)->int:
Call Function Execute a function. greet()

Function Building Blocks

These are the most common elements you’ll use when writing Python functions.

Feature Purpose
def Create a function.
Parameters Receive input values.
return Send a value back.
*args Unlimited positional arguments.
**kwargs Unlimited keyword arguments.
lambda Short anonymous function.
Type Hints Improve readability and tooling.
Docstring Explain what the function does.
Pro Tip: Write small functions that perform one task well. Functions with a single responsibility are easier to understand, test and reuse.
Common Mistake: Don’t forget to use return when your function should produce a value. Without it, Python automatically returns None.

Built-in Functions

Python includes many powerful built-in functions that let you work with data, perform calculations, iterate over collections and inspect objects without importing additional modules.

Function Description Example Copy
len() Return the number of items. len(items)
sum() Calculate the total. sum(numbers)
min() Return the smallest value. min(numbers)
max() Return the largest value. max(numbers)
sorted() Return a sorted copy. sorted(items)
reversed() Iterate in reverse order. reversed(items)
enumerate() Return index and value. enumerate(items)
zip() Combine multiple iterables. zip(a, b)
map() Apply a function to every item. map(str, numbers)
filter() Filter matching values. filter(is_even, numbers)
any() Return True if any value is true. any(flags)
all() Return True if all values are true. all(flags)
abs() Return absolute value. abs(-10)
round() Round a number. round(3.14159, 2)
type() Return an object’s type. type(value)
isinstance() Check an object’s type. isinstance(x, int)
range() Create a sequence of numbers. range(10)
input() Read user input. input("Name: ")
print() Display output. print(value)

Most Frequently Used Built-in Functions

If you’re learning Python, these are the built-in functions you’ll use most often.

Task Function
Count items len()
Calculate total sum()
Find minimum min()
Find maximum max()
Sort values sorted()
Loop with index enumerate()
Combine iterables zip()
Check object type type()
Validate object type isinstance()
Read user input input()
Print output print()
Pro Tip: Mastering Python’s built-in functions will make your code shorter, more readable and more Pythonic. Always check whether a built-in function already solves your problem before writing custom code.
Common Mistake: Remember that functions like sorted() return a new object, while methods such as list.sort() modify the original list in place.

Modules

Modules allow you to organize code into reusable files and access Python’s extensive standard library. Use the import statement to include modules and their functionality in your programs.

Syntax Description Example Copy
import Import an entire module. import math
from ... import Import specific objects. from math import sqrt
as Create an alias. import numpy as np
math Mathematical functions. math.sqrt(25)
random Generate random values. random.randint(1,10)
datetime Work with dates and times. datetime.now()
os Interact with the operating system. os.getcwd()
pathlib Modern file path handling. Path("file.txt")
sys Access Python runtime information. sys.version
json Read and write JSON data. json.loads(text)
collections Specialized container types. Counter(items)
itertools Efficient looping tools. product(a,b)

Popular Standard Library Modules

These built-in modules cover many everyday programming tasks and require no additional installation.

Module Typical Use
math Mathematics and calculations
random Random numbers and selections
datetime Date and time handling
os Operating system interaction
pathlib File and directory paths
json JSON serialization
sys Python interpreter information
collections Advanced data structures
itertools Efficient iteration utilities
Pro Tip: Always prefer Python’s standard library before installing third-party packages. It is well-tested, fast, and available in every Python installation.
Common Mistake: Avoid using from module import *. Import only what you need to keep your code readable and prevent naming conflicts.

File Handling

File handling lets you read from and write to files using Python. The safest and most common approach is to use with open(), which automatically closes the file after the block finishes.

Syntax Description Example Copy
open() Open a file. open("file.txt")
with open() Open and automatically close a file. with open("file.txt") as f:
"r" Read mode. open("file.txt", "r")
"w" Write mode. Overwrites existing content. open("file.txt", "w")
"a" Append mode. Adds content to the end. open("file.txt", "a")
read() Read the entire file. content = f.read()
readline() Read one line. line = f.readline()
readlines() Read all lines into a list. lines = f.readlines()
write() Write text to a file. f.write("Hello")
writelines() Write multiple lines. f.writelines(lines)
close() Close a file manually. f.close()

Common File Modes

Use the correct file mode depending on whether you want to read, write or append data.

Mode Meaning Behavior
r Read Opens an existing file for reading.
w Write Creates or overwrites a file.
a Append Adds content to the end of a file.
x Create Creates a new file and fails if it already exists.
b Binary Used for binary files such as images.
t Text Default text mode.
Pro Tip: Use with open() instead of manually calling close(). It is safer, cleaner and automatically closes the file even if an error occurs.
Common Mistake: Be careful with "w" mode. It overwrites the existing file content. Use "a" if you want to add new content without deleting old data.

Exception Handling

Exception handling allows your program to detect and respond to runtime errors without crashing. Python uses try, except, else and finally blocks to handle exceptions gracefully.

Keyword Description Example Copy
try Wrap code that may raise an exception. try:
except Handle an exception. except ValueError:
else Run if no exception occurs. else:
finally Always execute this block. finally:
raise Raise an exception manually. raise ValueError()
assert Debug assertion. assert x > 0
FileNotFoundError File does not exist. except FileNotFoundError:
ValueError Invalid value supplied. except ValueError:
TypeError Wrong object type. except TypeError:
ZeroDivisionError Division by zero. except ZeroDivisionError:

Exception Flow

A typical exception handling block follows this execution order.

Step Purpose
try Execute code that may fail.
except Handle matching exceptions.
else Run when no exception occurs.
finally Always execute cleanup code.
Pro Tip: Catch specific exceptions whenever possible. Handling ValueError or FileNotFoundError makes debugging much easier than catching every exception with Exception.
Common Mistake: Avoid using a bare except: statement. It catches every exception, including unexpected ones, which can hide bugs and make debugging difficult.
COMPLETE GUIDE

Table of Contents

Jump directly to any section of the complete Python guide. Each chapter builds on the previous one, making it easy to learn Python step by step.

GETTING STARTED

Getting Started with Python

Python is one of the world’s most popular programming languages. It’s known for its simple syntax, readability, and versatility, making it an excellent choice for beginners while remaining powerful enough for professional developers.

Why Learn Python?

Benefit Description
Easy to Learn Readable syntax with minimal boilerplate code.
Versatile Used for web development, automation, AI, data science, scripting and more.
Huge Community Millions of developers and thousands of open-source libraries.
Cross-Platform Runs on Windows, macOS and Linux.
Career Opportunities One of the most in-demand programming languages worldwide.

Common Uses of Python

Field Popular Libraries
Web Development Django, Flask, FastAPI
Automation os, pathlib, subprocess
Data Science NumPy, Pandas, Matplotlib
Machine Learning TensorFlow, PyTorch, Scikit-learn
Data Visualization Plotly, Seaborn, Matplotlib
Game Development Pygame
Cybersecurity Scapy, Requests
Did You Know? Python consistently ranks among the world’s most popular programming languages and is widely used by companies such as Google, Microsoft, Netflix, Spotify, Instagram and NASA.
INSTALLATION

How to Install Python

Before writing Python code, install Python 3 and verify that it works from your terminal or command prompt. The exact steps depend on your operating system.

Install Python on Windows

  1. Visit the official Python download page and download the current Python 3 installer for Windows.
  2. Open the downloaded installer.
  3. Follow the installation prompts and allow Python to be available from the command line.
  4. Finish the installation and open Command Prompt or PowerShell.
Command Prompt
python --version

You may also need:

Command Prompt
py --version

Install Python on macOS

  1. Download the macOS installer from the official Python website.
  2. Open the installer package and follow the installation steps.
  3. Open Terminal after the installation finishes.
  4. Verify the installation using the command below.
Terminal
python3 --version

Install Python on Linux

Python is often already installed on Linux. Check the installed version before installing anything.

Terminal
python3 --version

If Python is missing, install it using your Linux distribution’s package manager.

Distribution Example Command Copy
Ubuntu / Debian sudo apt install python3
Fedora sudo dnf install python3
Arch Linux sudo pacman -S python

Run Your First Python Program

Create a new file named hello.py and add the following code:

Python
print("Hello, World!")

Run the file:

Windows
python hello.py
macOS / Linux
python3 hello.py
Expected output
Hello, World!

Set Up Python in VS Code

  1. Install Visual Studio Code.
  2. Open the Extensions panel.
  3. Search for and install the official Python extension.
  4. Open your Python project folder.
  5. Select the correct Python interpreter when prompted.
  6. Open a .py file and run it from the editor.
Pro Tip: Use python --version on Windows and python3 --version on macOS or Linux to confirm which Python command is available on your system.
Common Mistake: If the terminal says Python is not recognized, close and reopen the terminal after installation. If the problem remains, Python may not be available in your system PATH.
PYTHON BASICS

Python Syntax

Python uses clean, readable syntax and indentation to define code blocks. Unlike many other programming languages, Python does not require braces or semicolons for normal statements.

Basic Python Syntax Rules

Rule Description Example
Indentation Defines code blocks. if active:
Colon Starts an indented block. for item in items:
Comments Begin with a hash symbol. # This is a comment
Case Sensitive Uppercase and lowercase names are different. name != Name
Line Breaks Usually end a statement. total = price + tax
Semicolons Allowed but normally unnecessary. x = 1; y = 2

Indentation

Indentation is required in Python. The standard convention is four spaces for each indentation level.

Python
Common Mistake: Code inside the same block must use consistent indentation. Mixing tabs and spaces can cause an IndentationError.

Comments

Comments explain code and are ignored by the Python interpreter.

Python
# Calculate the final price
price = 100
tax = 0.25
total = price * (1 + tax)

Multi-Line Statements

Long expressions can span multiple lines when enclosed in parentheses, brackets or braces.

Python
total = (
    product_price
    + shipping_cost
    + tax
)

Lists can also span several lines:

Python
languages = [
    "Python",
    "JavaScript",
    "SQL",
]

Case Sensitivity

Python is case-sensitive, which means these variables are treated as different names.

Python
name = "Alice"
Name = "Bob"

print(name)
print(Name)
Expected output
Alice
Bob

Statements on One Line

Python allows multiple statements on one line using semicolons, but this style is generally discouraged because it reduces readability.

Avoid
x = 10; y = 20; print(x + y)

Prefer this:

Recommended
x = 10
y = 20
print(x + y)
Pro Tip: Follow the PEP 8 style guide: use four spaces for indentation, keep statements readable and prefer one statement per line.
VARIABLES

Variables and Naming Rules

Variables store data that your program can use later. Python variables are created automatically when you assign a value—no type declaration is required.

Creating Variables

Assign a value using the equals sign (=).

Python
name = "Alice"
age = 28
height = 1.75
is_student = False

Variable Naming Rules

Rule Example
Must begin with a letter or underscore name, _count
Cannot begin with a number ❌ 2name
May contain numbers user1
Case-sensitive ageAge
No spaces first_name
No reserved keywords ❌ class, ❌ for

Multiple Assignment

Python allows assigning several variables in one line.

Python
x, y, z = 1, 2, 3

Swapping Variables

Python can swap variables without using a temporary variable.

Python
a = 10
b = 20

a, b = b, a

print(a)
print(b)
Expected Output
20
10

Constants

Python doesn’t have true constants, but uppercase names indicate values that shouldn’t change.

Python
PI = 3.14159
MAX_USERS = 100
Best Practice: Use descriptive variable names like customer_name instead of x or a. Clear names make code easier to read and maintain.
Common Mistake: Avoid naming variables after Python built-in functions such as list, str, dict or type. Doing so can lead to confusing errors later in your code.
DATA TYPES

Python Data Types

Every value in Python has a data type. Understanding data types is essential because they determine what operations you can perform and how data is stored and manipulated.

Built-in Data Types

Type Description Example
int Whole numbers 42
float Decimal numbers 3.14
str Text "Hello"
bool True or False True
list Ordered collection [1,2,3]
tuple Immutable collection (1,2,3)
set Unique values {1,2,3}
dict Key-value pairs {"name":"John"}
NoneType No value None

Checking a Data Type

Use the built-in type() function to inspect the type of an object.

Python
age = 25

print(type(age))
print(type("Python"))
print(type(True))
Expected Output
<class 'int'>
<class 'str'>
<class 'bool'>

Type Conversion

Python allows converting values between compatible data types.

Function Purpose Example
int() Convert to integer int("10")
float() Convert to float float("5.2")
str() Convert to string str(100)
bool() Convert to boolean bool(1)
list() Create a list list("abc")

Mutable vs Immutable

Mutable Immutable
list tuple
dict str
set int
float
bool

Mutable objects can be modified after creation. Immutable objects cannot be changed once created.

Truthy and Falsy Values

In Python, every object evaluates to either True or False in conditional statements.

Truthy Falsy
1 0
“Hello” “”
[1] []
{“a”:1} {}
True False
None
Best Practice: Choose the correct data type for the job. Using the appropriate type makes code easier to read, improves performance and reduces bugs.
Common Mistake: Do not compare different data types without understanding how conversion works. For example, the string "10" is not the same as the integer 10.
OPERATORS

Python Operators

Operators perform calculations, compare values, assign variables and evaluate logical expressions. Python includes arithmetic, comparison, logical, assignment, identity and membership operators.

Arithmetic Operators

Operator Description Example Result
+ Addition 5 + 2 7
- Subtraction 5 - 2 3
* Multiplication 5 * 2 10
/ Division 5 / 2 2.5
// Floor division 5 // 2 2
% Modulo 5 % 2 1
** Exponent 5 ** 2 25

Comparison Operators

Operator Description Example
==Equal tox == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equalx >= y
<=Less than or equalx <= y

Logical Operators

Operator Description Example
and Both conditions must be true. x > 0 and y > 0
or One condition must be true. x > 0 or y > 0
not Reverses a boolean value. not active

Assignment Operators

Operator Equivalent
+=x = x + 1
-=x = x – 1
*=x = x * 2
/=x = x / 2
//=x = x // 2
%=x = x % 2
**=x = x ** 2

Identity vs Equality

The == operator compares values, while is checks whether two variables reference the same object.

Python
a = [1,2,3]
b = [1,2,3]

print(a == b)
print(a is b)
Expected Output
True
False

Membership Operators

Python
fruits = ["apple", "banana", "orange"]

print("banana" in fruits)
print("pear" not in fruits)
Expected Output
True
True
Best Practice: Use == to compare values and reserve is primarily for comparisons with None (for example, if value is None:).
Common Mistake: Beginners often confuse == with =. Remember that = assigns a value, while == compares two values.
STRINGS

Working with Strings in Python

Strings are one of the most commonly used data types in Python. They represent text and provide many built-in methods for searching, formatting, splitting and manipulating data.

Creating Strings

Strings can be enclosed in either single or double quotes.

Python
name = "Alice"

city = 'London'

message = """Hello
World"""

String Indexing

Each character has an index starting at 0. Negative indexes count from the end.

Python
text = "Python"

print(text[0])

print(text[3])

print(text[-1])
Expected Output
P
h
n

String Slicing

Slicing extracts part of a string using the syntax [start:end].

Python
text = "Python"

print(text[0:3])

print(text[2:])

print(text[:4])

print(text[::-1])
Expected Output
Pyt
thon
Pyth
nohtyP
Pro Tip: Negative indexes are extremely useful when working with filenames, extensions and text where you need characters from the end of the string.

Escape Characters

Escape characters let you include special characters inside strings, such as quotation marks, tabs and new lines.

Escape Description Output
\n New line Line break
\t Tab Horizontal tab
\\ Backslash \
\" Double quote
\' Single quote
Python
print("Hello\nWorld")
print("Name:\tJohn")
print("She said \"Hi\"")

Concatenation

Concatenation joins two or more strings together using the + operator.

Python
first = "John"
last = "Doe"

full_name = first + " " + last

print(full_name)
Expected Output
John Doe

Repeating Strings

Multiply a string by an integer to repeat it multiple times.

Python
print("-" * 30)
print("Hi! " * 3)
Expected Output
------------------------------
Hi! Hi! Hi!

String Formatting

Python provides multiple ways to insert variables into strings. Modern Python code should generally use f-strings.

Method Example
f-string ⭐ f"Hello {name}"
format() "Hello {}".format(name)
% formatting "Hello %s" % name

Using f-Strings

f-Strings are the recommended way to build readable and efficient strings.

Python
name = "Alice"
age = 30

print(f"{name} is {age} years old.")
Expected Output
Alice is 30 years old.
Best Practice: Prefer f-strings for new Python code. They are easier to read, faster than most alternatives, and support inline expressions.

Common String Methods

Python provides many built-in methods for working with strings. The methods below are among the most frequently used in everyday programming.

Method Description Example
upper() Convert to uppercase. "python".upper()
lower() Convert to lowercase. "Python".lower()
strip() Remove leading and trailing whitespace. " text ".strip()
replace() Replace part of a string. text.replace("a","b")
split() Split into a list. text.split(",")
join() Join iterable into one string. ", ".join(items)
find() Return index of first match. text.find("Py")
count() Count occurrences. text.count("a")
startswith() Check beginning. text.startswith("Py")
endswith() Check ending. text.endswith(".py")
isdigit() Check if all characters are digits. "123".isdigit()
isalpha() Check if all characters are letters. "Python".isalpha()
isalnum() Letters and numbers only. "abc123".isalnum()

Most Useful String Methods Example

Python
text = "  Python Cheat Sheet  "

print(text.strip())
print(text.upper())
print(text.lower())
print(text.replace("Python", "Java"))
print(text.startswith(" "))
print(text.endswith("Sheet  "))
Expected Output
Python Cheat Sheet
  PYTHON CHEAT SHEET
  python cheat sheet
  Java Cheat Sheet
True
True

Searching Inside Strings

Use these methods to search for characters or words without manually looping through the string.

Python
text = "Learn Python"

print("Python" in text)
print(text.find("Python"))
print(text.count("n"))
Expected Output
True
6
2
Best Practice: Use built-in string methods instead of writing manual loops whenever possible. They are faster, easier to read and optimized by Python.
Common Mistake: Remember that string methods return a new string. Since strings are immutable, methods like replace() and upper() do not modify the original string.
LISTS

Python Lists

Lists are ordered, mutable collections that can store multiple values in a single variable. They are one of the most commonly used data structures in Python.

Creating a List

Create a list using square brackets. List items can contain the same or different data types.

Python
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4]
mixed = ["Python", 3.12, True]

List Indexes

List indexes begin at 0. Negative indexes count backward from the end.

0 1 2 3
Dog Cat Fox Cow
-4 -3 -2 -1
Python
animals = ["Dog", "Cat", "Fox", "Cow"]

print(animals[0])
print(animals[2])
print(animals[-1])
Expected Output
Dog
Fox
Cow

Changing List Items

Lists are mutable, which means their values can be changed after creation.

Python
fruits = ["apple", "banana", "orange"]

fruits[1] = "mango"

print(fruits)
Expected Output
["apple", "mango", "orange"]

Adding and Removing Items

Method Purpose Example
append() Add one item to the end. items.append("apple")
extend() Add multiple items. items.extend(other)
insert() Add an item at a position. items.insert(0, "apple")
remove() Remove the first matching value. items.remove("apple")
pop() Remove and return an item. items.pop()
clear() Remove all items. items.clear()

List Slicing

Use slicing to extract part of a list with [start:end:step]. The ending index is not included.

Python
numbers = [0, 1, 2, 3, 4, 5]

print(numbers[1:4])
print(numbers[:3])
print(numbers[::2])
print(numbers[::-1])
Expected Output
[1, 2, 3]
[0, 1, 2]
[0, 2, 4]
[5, 4, 3, 2, 1, 0]

Looping Through Lists

Python
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)

List Comprehensions

List comprehensions provide a compact way to create a new list from an iterable.

Python
numbers = [1, 2, 3, 4, 5]

squares = [number ** 2 for number in numbers]
even_numbers = [number for number in numbers if number % 2 == 0]

print(squares)
print(even_numbers)
Expected Output
[1, 4, 9, 16, 25]
[2, 4]
Best Practice: Use list comprehensions for short and readable transformations. Use a normal for loop when the logic becomes complex.
Common Mistake: Assigning one list to another variable does not create an independent copy. Use items.copy() or items[:] when you need a separate list.
TUPLES

Python Tuples

Tuples are ordered, immutable collections used to store multiple values. Unlike lists, tuples cannot be modified after they are created, making them faster and ideal for fixed data.

Creating Tuples

Create tuples using parentheses. A single-item tuple requires a trailing comma.

Python
colors = ("red", "green", "blue")

numbers = (1, 2, 3)

single = ("apple",)

Tuple Indexes

Tuple indexing works exactly like lists.

0 1 2 3
Red Green Blue Black
-4 -3 -2 -1
Python
colors = ("red", "green", "blue")

print(colors[0])

print(colors[-1])
Expected Output
red
blue

Tuple Methods

Method Description Example
count() Count occurrences. items.count("red")
index() Return first matching index. items.index("blue")

Tuple Packing and Unpacking

Python can automatically pack values into a tuple and unpack them into variables.

Python
person = ("John", 30)

name, age = person

print(name)

print(age)
Expected Output
John
30

Tuple vs List

Feature Tuple List
Mutable ❌ No ✅ Yes
Ordered ✅ Yes ✅ Yes
Duplicate Values ✅ Allowed ✅ Allowed
Performance Faster Slightly slower
Typical Use Fixed data Dynamic data
Best Practice: Use tuples for values that should never change, such as coordinates, RGB colors, dates and configuration values.
Common Mistake: Remember that parentheses alone do not create a single-item tuple. Always include the trailing comma: ("apple",)

Quick Summary

Data Structure Ordered Mutable Duplicates Typical Use
List Dynamic collections
Tuple Fixed data
Remember: Use a List when data needs to change. Use a Tuple when values should remain constant.
SETS

Python Sets

A set is an unordered collection of unique values. Sets automatically remove duplicates and provide fast membership testing, making them ideal for filtering unique items and performing mathematical set operations.

Creating Sets

Create a set using curly braces or the set() constructor.

Python
fruits = {"apple", "banana", "orange"}

numbers = {1, 2, 3, 4}

letters = set(["a", "b", "c"])

Set Characteristics

Feature Supported?
Ordered ❌ No
Mutable ✅ Yes
Duplicate Values ❌ Automatically removed
Indexing ❌ Not supported
Fast Membership Testing ✅ Yes

Removing Duplicates

Python
numbers = [1,2,2,3,3,4,5]

unique = set(numbers)

print(unique)

Common Set Methods

Method Description
add() Add an element.
update() Add multiple elements.
remove() Remove an element.
discard() Remove without raising an error.
pop() Remove a random element.
clear() Remove all elements.

Set Operations

Python
a = {1,2,3}
b = {3,4,5}

print(a | b)
print(a & b)
print(a - b)
print(a ^ b)
Expected Output
{1,2,3,4,5}
{3}
{1,2}
{1,2,4,5}

Set Operators

Operator Meaning
| Union
& Intersection
- Difference
^ Symmetric Difference

Quick Summary

Remember Value
Ordered ❌ No
Mutable ✅ Yes
Duplicates ❌ Removed
Indexing ❌ No
Best Use Unique values
Best Practice: Use sets whenever you only care about unique values or need very fast membership testing.
Interview Question: Why are sets generally faster than lists when checking if an element exists?

Because sets are implemented using hash tables, allowing average O(1) lookup time, while lists require scanning elements one by one with average O(n) complexity.

DICTIONARIES

Python Dictionaries

Dictionaries store data as key-value pairs. They are one of Python’s most powerful and frequently used data structures, providing fast lookups and organized access to data.

Creating Dictionaries

Create a dictionary using curly braces with keys and values separated by colons.

Python
person = {
    "name": "John",
    "age": 30,
    "country": "USA"
}

print(person)

Dictionary Structure

Think of a dictionary as a collection of labels (keys) connected to values.

“name” ➜ “John”
“age” ➜ 30
“country” ➜ “USA”

Accessing Values

Python
person = {
    "name": "John",
    "age": 30
}

print(person["name"])
print(person["age"])
Expected Output
John
30

Adding and Updating Values

Python
person = {
    "name": "John"
}

person["age"] = 30

person["name"] = "Alice"

print(person)

Common Dictionary Methods

Method Description
get() Safely retrieve a value.
keys() Return all keys.
values() Return all values.
items() Return key-value pairs.
update() Update multiple values.
pop() Remove a key.
clear() Remove everything.

Looping Through Dictionaries

Python
person = {
    "name":"John",
    "age":30,
    "country":"USA"
}

for key, value in person.items():
    print(key, value)

Dictionary vs List

Feature Dictionary List
Access By key By index
Lookup Speed Very Fast Linear
Ordered ✅ Yes (Python 3.7+) ✅ Yes
Duplicate Keys ❌ No ✅ Yes

Quick Summary

Remember Value
Stores Key-value pairs
Ordered ✅ Yes
Mutable ✅ Yes
Fast Lookup ✅ O(1) average
Best Use Structured data
Best Practice: Use dictionaries whenever data naturally has names or identifiers. They make code more readable than relying on numeric indexes.
Interview Question: What is the difference between [] and .get() when reading a dictionary?

Using [] raises a KeyError if the key doesn’t exist. The get() method safely returns None (or a default value you specify), making it the preferred choice when a key may be missing.

CONDITIONALS

Python Conditionals (if, elif, else)

Conditional statements allow your program to make decisions. They execute different blocks of code depending on whether a condition evaluates to True or False.

The if Statement

Use if when code should only run if a condition is true.

Python
age = 16

if age >= 18:
    print("Adult")
else:
    print("Minor")
Expected Output
Minor

if…elif…else

Use elif when you need multiple conditions.

Python
age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("Entry allowed")

Nested if Statements

Python
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)
Expected Output
apple
banana
orange

range()

Expression Result
range(5) 0 → 4
range(2,8) 2 → 7
range(0,10,2) 0,2,4,6,8
Python
for i in range(5):
    print(i)

while Loop

Python
count = 1

while count <= 5:
    print(count)
    count += 1

break

Python
for i in range(10):

    if i == 5:
        break

    print(i)

continue

Python
for i in range(5):

    if i == 2:
        continue

    print(i)

enumerate()

Python
fruits = ["apple","banana","orange"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

zip()

Python
names = ["John","Anna"]
ages = [25,30]

for name, age in zip(names, ages):
    print(name, age)

Quick Summary

Keyword Purpose
forIterate over a sequence.
whileRepeat while condition is true.
breakExit the loop.
continueSkip current iteration.
enumerate()Get index and value.
zip()Loop over multiple iterables.
Best Practice: Use for loops whenever possible. Reserve while for situations where the number of iterations isn't known in advance.
Common Mistake: Don't forget to update the loop variable in a while loop, otherwise you'll create an infinite loop.
FUNCTIONS

Python Functions

Functions organize reusable code into named blocks. They reduce repetition, improve readability and make programs easier to test and maintain.

Defining and Calling a Function

Use def to define a function. The indented code runs when the function is called.

Python
def greet():
    print("Hello!")

greet()
Expected Output
Hello!

Parameters and Arguments

Parameters are names defined by the function. Arguments are the values supplied when calling it.

Python
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
Expected Output
Hello, Alice!

Returning Values

Use return to send a value back to the caller.

Python
def add(a, b):
    return a + b

result = add(5, 3)
print(result)
Expected Output
8

Default Parameters

Default values are used when an argument is not provided.

Python
def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()
greet("John")
Expected Output
Hello, Guest!
Hello, John!

Keyword Arguments

Keyword arguments identify values by parameter name, so their order can be changed.

Python
def create_user(name, age, active):
    print(name, age, active)

create_user(age=30, active=True, name="Alice")

*args and **kwargs

Syntax Purpose Received As
*args Accept any number of positional arguments. Tuple
**kwargs Accept any number of keyword arguments. Dictionary
Python
def total(*numbers):
    return sum(numbers)

print(total(10, 20, 30))
Expected Output
60
Python
def show_user(**user):
    for key, value in user.items():
        print(key, value)

show_user(name="Alice", age=30)

Multiple Return Values

Python can return multiple values as a tuple.

Python
def calculate(a, b):
    return a + b, a * b

total, product = calculate(4, 5)

print(total)
print(product)
Expected Output
9
20

Function Scope

Variables created inside a function are local and normally cannot be used outside it.

Python
message = "Global"

def show_message():
    message = "Local"
    print(message)

show_message()
print(message)
Expected Output
Local
Global

Docstrings

A docstring documents what a function does, its arguments and its return value.

Python
def add(a, b):
    """Return the sum of two numbers."""
    return a + b

print(add.__doc__)

Quick Summary

Feature Purpose
def Define a function.
return Send a result back.
Default parameter Provide a fallback value.
*args Collect positional arguments.
**kwargs Collect keyword arguments.
Docstring Document the function.
Best Practice: Give functions descriptive names and keep each function focused on one clear task.
Common Mistake: Do not use mutable values such as lists or dictionaries as default parameters. Use None and create the collection inside the function instead.
LAMBDA FUNCTIONS

Python Lambda Functions

Lambda functions are small anonymous functions defined with the lambda keyword. They are useful for short, simple operations that don't require a full function definition.

Lambda Syntax

A lambda function can take any number of arguments but can only contain a single expression.

Python
square = lambda x: x * x

print(square(5))
Expected Output
25

Multiple Arguments

Lambda functions can accept multiple arguments.

Python
multiply = lambda a, b: a * b

print(multiply(4, 6))
Expected Output
24

Using Lambda with sorted()

Lambda functions are commonly used as sorting keys.

Python
people = [
    ("John", 25),
    ("Alice", 30),
    ("Bob", 20)
]

people.sort(key=lambda person: person[1])

print(people)

Using Lambda with map()

Python
numbers = [1,2,3,4]

squared = list(map(lambda x: x**2, numbers))

print(squared)
Expected Output
[1, 4, 9, 16]

Using Lambda with filter()

Python
numbers = [1,2,3,4,5,6]

even = list(filter(lambda x: x % 2 == 0, numbers))

print(even)
Expected Output
[2, 4, 6]

Lambda vs Regular Function

Feature Lambda Regular Function
Name Anonymous Named
Statements One expression Multiple statements
Best Use Short operations Complex logic
Readability Simple tasks Better for larger code

Quick Summary

Remember Value
Keyword lambda
Multiple arguments ✅ Yes
Multiple statements ❌ No
Returns value Automatically
Typical use map(), filter(), sorted()
Best Practice: Use lambda functions only for short, readable expressions. If the logic becomes complex, use a regular function with def.
Common Mistake: Trying to write complex business logic inside a lambda expression usually makes code harder to read. Keep lambda functions simple.
MODULES

Python Modules

Modules allow you to organize code into reusable files and import functionality written by yourself or other developers. Python also includes a large standard library with hundreds of built-in modules.

Importing a Module

Use the import keyword to access functions, classes and variables from another module.

Python
import math

print(math.sqrt(25))
print(math.pi)
Expected Output
5.0
3.141592653589793

Import Specific Functions

Import only the functions you need to keep your code concise.

Python
from math import sqrt

print(sqrt(81))
Expected Output
9.0

Import with an Alias

Aliases shorten long module names and improve readability.

Python
import numpy as np

array = np.array([1,2,3])

print(array)

Creating Your Own Module

Any Python file (.py) can become a module.

calculator.py
def add(a, b):
    return a + b

Use your custom module:

main.py
import calculator

print(calculator.add(5, 3))

Popular Standard Library Modules

Module Purpose
math Mathematical functions
random Random numbers and choices
datetime Dates and times
os Operating system interaction
pathlib Modern file system paths
json Read and write JSON data
csv CSV file handling
collections Advanced data structures
itertools Efficient looping utilities
statistics Statistical calculations

Built-in vs Third-Party Modules

Type Examples Installation Required
Built-in math, os, json ❌ No
Third-party NumPy, Pandas, Requests ✅ Yes (pip)

Installing Third-Party Packages

Terminal
pip install requests

pip install pandas

pip install numpy

Quick Summary

Keyword Purpose
import Import an entire module
from Import specific objects
as Create an alias
pip Install third-party packages
Best Practice: Import only what you need and place all imports at the top of your Python files. Use aliases such as import numpy as np only when they are widely recognized.
Common Mistake: Avoid using from module import *. It imports everything into the current namespace, making your code harder to read and increasing the risk of naming conflicts.
FILE HANDLING

Python File Handling

Python makes it easy to create, read, write and manage files. File handling is commonly used for configuration files, logs, CSV data, reports and text processing.

Opening a File

Use the built-in open() function to open a file.

Python
file = open("example.txt", "r")

print(file.read())

file.close()

File Modes

Mode Description
r Read (default)
w Write (overwrites existing file)
a Append to the end of a file
x Create a new file
rb Read binary files
wb Write binary files

Reading Files

Python
with open("example.txt", "r") as file:

    print(file.read())

Read Line by Line

Python
with open("example.txt") as file:

    for line in file:
        print(line.strip())

Writing Files

Python
with open("example.txt", "w") as file:

    file.write("Hello World")

Appending to a File

Python
with open("example.txt", "a") as file:

    file.write("\nAnother line")

Why Use with?

Without with With with
Must call close() Automatically closes the file
Higher risk of resource leaks Safer and cleaner code
Less readable Recommended approach

Quick Summary

Mode Purpose
r Read
w Write
a Append
x Create
with Automatically closes files
Best Practice: Always use the with statement when working with files. It automatically closes the file, even if an exception occurs.
Common Mistake: Opening a file with mode "w" deletes all existing content before writing new data. Use "a" if you want to preserve the existing contents.

readline() and readlines()

Use readline() to read one line at a time or readlines() to read every line into a list.

Python
with open("example.txt") as file:

    first_line = file.readline()

    all_lines = file.readlines()

print(first_line)
print(all_lines)

seek() and tell()

Move the file pointer or check its current position.

Python
with open("example.txt") as file:

    print(file.tell())

    file.seek(0)

    print(file.tell())

Working with CSV Files

Python
import csv

with open("people.csv") as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

Working with JSON Files

Python
import json

with open("user.json") as file:

    data = json.load(file)

print(data)

Checking if a File Exists

Python
from pathlib import Path

file = Path("example.txt")

print(file.exists())

Deleting Files

Python
import os

os.remove("example.txt")

Renaming Files

Python
import os

os.rename("old.txt", "new.txt")

Useful pathlib Methods

Method Description
exists() Check if a file exists.
is_file() Check if the path is a file.
is_dir() Check if the path is a directory.
mkdir() Create a directory.
unlink() Delete a file.
rename() Rename a file.

Quick Summary

Task Function
Read file open(...,"r")
Write file open(...,"w")
Append file open(...,"a")
CSV csv
JSON json
Modern paths pathlib
Best Practice: Use pathlib instead of os.path for new Python projects. Its object-oriented API is cleaner, easier to read and works consistently across operating systems.
Interview Question: Why is with open(...) preferred over calling open() and close() manually?

The with statement automatically closes the file even if an exception occurs, preventing resource leaks and making the code cleaner and safer.

EXCEPTION HANDLING

Python Exception Handling

Exceptions are runtime errors that interrupt the normal flow of a program. Python provides try, except, else and finally to handle errors gracefully instead of crashing your application.

Basic try...except

Use try to execute code that may fail and except to handle errors.

Python
try:
    print(10 / 0)

except ZeroDivisionError:
    print("Cannot divide by zero.")
Expected Output
Cannot divide by zero.

Handling Multiple Exceptions

Python
try:
    number = int(input("Enter a number: "))
    print(100 / number)

except ValueError:
    print("Please enter a valid number.")

except ZeroDivisionError:
    print("Number cannot be zero.")

Using else

The else block executes only if no exception occurs.

Python
try:
    result = 20 / 5

except ZeroDivisionError:
    print("Error")

else:
    print(result)

Using finally

The finally block always runs, even if an exception occurs.

Python
try:
    file = open("example.txt")

finally:
    file.close()

Raising Exceptions

Use raise to trigger your own exception.

Python
age = -5

if age < 0:
    raise ValueError("Age cannot be negative.")

Common Built-in Exceptions

Exception Occurs When
ValueError Wrong value type or format.
TypeError Invalid operation between types.
IndexError Invalid list index.
KeyError Dictionary key doesn't exist.
FileNotFoundError File cannot be found.
ZeroDivisionError Division by zero.
AttributeError Object has no such attribute.
NameError Variable doesn't exist.

Quick Summary

Keyword Purpose
try Execute risky code.
except Handle an exception.
else Runs if no exception occurred.
finally Always executes.
raise Throw an exception manually.
Best Practice: Catch only the exceptions you expect. Handling specific exceptions makes debugging much easier than using a generic except: block.
Common Mistake: Avoid empty except: blocks that silently ignore all errors. Unexpected exceptions should usually be logged or re-raised.
Interview Question: Why is catching Exception or using a bare except: generally discouraged?

Because it hides unexpected bugs and can also catch system-level exceptions that should normally terminate the program. Catch the most specific exception types whenever possible.

OBJECT-ORIENTED PROGRAMMING

Python Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm based on objects. Objects combine data (attributes) and behavior (methods), making code easier to organize, reuse and maintain.

What is a Class?

A class is a blueprint used to create objects. It defines what data and behavior an object will have.


Class
 │
 ├── Attributes
 │      name
 │      age
 │
 └── Methods
        speak()
        walk()

            │
            ▼

        Object

Creating Your First Class

Python
class Dog:

    pass

dog = Dog()

print(type(dog))
Expected Output
<class '__main__.Dog'>

The __init__ Constructor

The __init__() method runs automatically when a new object is created.

Python
class Dog:

    def __init__(self, name):

        self.name = name

dog = Dog("Buddy")

print(dog.name)
Expected Output
Buddy

Attributes vs Methods

Concept Description Example
Attribute Stores data dog.name
Method Performs an action dog.bark()

Creating Methods

Python
class Dog:

    def __init__(self, name):

        self.name = name

    def bark(self):

        print(f"{self.name} says Woof!")

dog = Dog("Buddy")

dog.bark()
Expected Output
Buddy says Woof!

Quick Summary

Term Meaning
Class Blueprint for objects.
Object Instance of a class.
Attribute Stores object data.
Method Function inside a class.
__init__() Constructor.
self Reference to the current object.
Best Practice: Use classes when multiple objects share the same structure and behavior. Avoid creating classes for very small scripts where simple functions are sufficient.

Inheritance

Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse.

Python
class Animal:

    def speak(self):
        print("Some sound")

class Dog(Animal):

    pass

dog = Dog()

dog.speak()
Expected Output
Some sound

Method Overriding

A child class can replace a method inherited from its parent.

Python
class Animal:

    def speak(self):
        print("Some sound")

class Dog(Animal):

    def speak(self):
        print("Woof!")

Dog().speak()
Expected Output
Woof!

Using super()

The super() function allows a child class to access methods from its parent.

Python
class Animal:

    def __init__(self, name):
        self.name = name

class Dog(Animal):

    def __init__(self, name, breed):

        super().__init__(name)

        self.breed = breed

dog = Dog("Buddy", "Golden Retriever")

print(dog.name)
print(dog.breed)
Expected Output
Buddy
Golden Retriever

Instance Variables vs Class Variables

Feature Instance Variable Class Variable
Belongs To Each object The class
Shared ❌ No ✅ Yes
Typical Use Object-specific data Shared constants
Python
class Dog:

    species = "Canine"

    def __init__(self, name):

        self.name = name

dog = Dog("Buddy")

print(dog.name)
print(dog.species)

Encapsulation

Encapsulation hides internal implementation details and protects object data.

Python
class BankAccount:

    def __init__(self):

        self.__balance = 1000

    def get_balance(self):

        return self.__balance

account = BankAccount()

print(account.get_balance())
Expected Output
1000

Quick Summary

Concept Purpose
Inheritance Reuse code from another class.
Method Overriding Replace inherited behavior.
super() Call parent class methods.
Class Variable Shared by every object.
Instance Variable Unique for each object.
Encapsulation Protect internal object data.
Best Practice: Favor composition over inheritance when classes do not have a clear "is-a" relationship. Inheritance should represent natural hierarchies such as Dog → Animal.
Common Mistake: Private attributes (prefixed with __) are name-mangled by Python. They are intended to discourage direct access, not provide strict security.

Polymorphism

Polymorphism allows different classes to implement the same method in their own way. The same interface can produce different behavior depending on the object.

Python
class Dog:

    def speak(self):
        return "Woof!"

class Cat:

    def speak(self):
        return "Meow!"

animals = [Dog(), Cat()]

for animal in animals:

    print(animal.speak())
Expected Output
Woof!
Meow!

@property

The @property decorator allows a method to be accessed like an attribute while keeping control over how the value is retrieved.

Python
class Circle:

    def __init__(self, radius):
        self.radius = radius

    @property
    def diameter(self):
        return self.radius * 2

circle = Circle(5)

print(circle.diameter)
Expected Output
10

Static Methods

Static methods belong to a class but do not access instance or class data.

Python
class Math:

    @staticmethod
    def square(x):
        return x * x

print(Math.square(8))
Expected Output
64

Class Methods

Class methods receive the class itself as the first parameter using cls.

Python
class Dog:

    species = "Canine"

    @classmethod
    def show_species(cls):
        print(cls.species)

Dog.show_species()
Expected Output
Canine

Dataclasses

The @dataclass decorator automatically generates common methods such as __init__(), __repr__() and __eq__().

Python
from dataclasses import dataclass

@dataclass
class Person:

    name: str
    age: int

person = Person("Alice", 30)

print(person)

Four Pillars of OOP

Pillar Description
Encapsulation Protect object data.
Inheritance Reuse existing classes.
Polymorphism One interface, multiple behaviors.
Abstraction Hide unnecessary implementation details.

Quick Summary

Concept Purpose
Polymorphism Different objects, same interface.
@property Method behaves like an attribute.
@staticmethod Utility function inside a class.
@classmethod Works with the class itself.
@dataclass Automatically generates boilerplate code.
Best Practice: Keep classes focused on a single responsibility. If a class becomes too large or handles unrelated tasks, consider splitting it into smaller classes.
Interview Question: What is the difference between a static method and a class method?

A @staticmethod does not receive either self or cls and behaves like a regular function inside a class. A @classmethod receives the class as its first argument (cls) and can access or modify class-level data.

GENERATORS

Python Generators

Generators produce values one at a time instead of storing them all in memory. They are memory-efficient, lazy-evaluated and ideal for processing large datasets or infinite sequences.

What is a Generator?

A generator function uses the yield keyword instead of return. Each call produces the next value while preserving the function's state.


Generator

yield → 1

yield → 2

yield → 3

yield → ...

(Produces one value at a time)

Creating a Generator

Python
def count():

    yield 1
    yield 2
    yield 3

for number in count():

    print(number)
Expected Output
1
2
3

yield vs return

yield return
Produces one value at a time Returns once and exits
Remembers execution state Function finishes
Memory efficient Stores full result

Using next()

The next() function manually retrieves the next value from a generator.

Python
def numbers():

    yield 10
    yield 20
    yield 30

gen = numbers()

print(next(gen))
print(next(gen))
print(next(gen))
Expected Output
10
20
30

Generator Expression

Generator expressions are similar to list comprehensions but use parentheses instead of square brackets.

Python
squares = (x**2 for x in range(5))

for value in squares:

    print(value)

Memory Comparison

List Generator
Stores every value Produces values on demand
Higher memory usage Very low memory usage
Good for small collections Ideal for large datasets
Can be reused Consumed after iteration

Infinite Generator

Python
def infinite():

    number = 1

    while True:

        yield number

        number += 1

This generator never ends and is useful for streams or continuous data processing.

Quick Summary

Feature Generator
Keyword yield
Memory Efficient ✅ Yes
Lazy Evaluation ✅ Yes
Reusable ❌ No
Best For Large datasets & streams
Best Practice: Choose generators when processing large files, APIs or datasets where loading everything into memory is unnecessary.
Common Mistake: Generators can only be iterated once. If you need to reuse the data multiple times, create a new generator or convert it to a list.
Interview Question: Why are generators more memory efficient than lists?

Generators produce values one at a time using yield instead of storing every value in memory. This makes them ideal for processing very large datasets or infinite sequences.

DECORATORS

Python Decorators

Decorators allow you to modify or extend the behavior of functions without changing their original code. They are widely used for logging, authentication, caching, timing and many Python frameworks such as Flask and Django.

What is a Decorator?

A decorator wraps another function and adds functionality before or after it runs.


Original Function

       │

       ▼

Decorator

       │

       ▼

Enhanced Function

Functions are First-Class Objects

Functions can be assigned to variables, passed as arguments and returned from other functions. This capability makes decorators possible.

Python
def greet():

    print("Hello!")

say_hello = greet

say_hello()
Expected Output
Hello!

Creating Your First Decorator

Python
def decorator(func):

    def wrapper():

        print("Before")

        func()

        print("After")

    return wrapper

@decorator

def greet():

    print("Hello!")

greet()
Expected Output
Before
Hello!
After

Decorator with Arguments

Use *args and **kwargs so the decorator works with any function signature.

Python
def decorator(func):

    def wrapper(*args, **kwargs):

        print("Running...")

        return func(*args, **kwargs)

    return wrapper

@decorator

def add(a, b):

    return a + b

print(add(4, 5))
Expected Output
Running...
9

Common Uses for Decorators

Use Case Description
Logging Record function calls.
Authentication Check user permissions.
Caching Store previous results.
Timing Measure execution time.
Validation Validate input arguments.
Retry Logic Retry failed operations.

Built-in Decorators

Decorator Purpose
@property Create computed attributes.
@staticmethod Define utility methods.
@classmethod Work with the class itself.
@dataclass Generate boilerplate code automatically.

Quick Summary

Concept Purpose
Decorator Wrap another function.
@ Decorator syntax.
*args Accept positional arguments.
**kwargs Accept keyword arguments.
Common Uses Logging, caching, authentication.
Best Practice: Keep decorators focused on one responsibility. A logging decorator should log, a caching decorator should cache. Small, reusable decorators are easier to maintain.
Common Mistake: If your decorator doesn't return the wrapper function, the decorated function will no longer work correctly. Always return the wrapper.
Interview Question: Why are *args and **kwargs commonly used inside decorators?

They allow the decorator to wrap functions with any number of positional and keyword arguments, making the decorator reusable across many different functions.

TYPE HINTS

Python Type Hints

Type hints allow you to specify the expected data types for variables, function parameters and return values. They improve code readability, enable better IDE support and help detect bugs before runtime.

Basic Type Hints

Use a colon (:) for variables and -> for function return types.

Python
name: str = "Alice"
age: int = 30
height: float = 1.72
active: bool = True

Function Type Hints

Annotate parameters and the return value to clearly document how a function should be used.

Python
def add(a: int, b: int) -> int:

    return a + b

print(add(5, 3))
Expected Output
8

Common Built-in Types

Type Hint Description
int Integer numbers
float Floating-point numbers
str Text strings
bool Boolean values
list Lists
dict Dictionaries
tuple Tuples
set Sets

Generic Collection Types

Specify the type of items stored inside collections.

Python
numbers: list[int] = [1, 2, 3]

names: list[str] = ["Alice", "Bob"]

scores: dict[str, int] = {
    "Alice": 95,
    "Bob": 88
}

coordinates: tuple[int, int] = (10, 20)

unique: set[str] = {"red", "blue"}

Optional Values

Use Optional when a value may be None.

Python
from typing import Optional

def get_name() -> Optional[str]:

    return None

Union Types (Python 3.10+)

The pipe operator (|) can specify multiple valid types.

Python
def square(value: int | float) -> float:

    return value * value

Most Useful typing Objects

Type Purpose
Optional Value may be None.
Any Accept any type.
Union Multiple possible types.
Callable Function type.
Iterable Any iterable object.
Generator Generator objects.

Quick Summary

Syntax Meaning
x: int Variable type
-> str Return type
list[int] List of integers
dict[str, int] Dictionary mapping strings to integers
int | float Multiple allowed types
Best Practice: Use type hints consistently in new projects. They improve readability, make IDE autocompletion more accurate and work well with static type checkers such as mypy.
Common Mistake: Type hints do not enforce types at runtime. They are primarily used for documentation, tooling and static analysis.
Interview Question: Why should you use type hints if Python is dynamically typed?

Type hints improve code readability, documentation, IDE support and static analysis. They help catch many bugs before the code is executed while preserving Python's dynamic nature.

VIRTUAL ENVIRONMENTS

Python Virtual Environments (venv)

A virtual environment is an isolated Python environment with its own interpreter and installed packages. It prevents dependency conflicts between projects and is considered a best practice for Python development.

Why Use a Virtual Environment?

Without virtual environments, installing packages globally can cause version conflicts between projects.


Without venv

Project A
└── requests 2.28

Project B
└── requests 2.32

❌ Version conflict


With venv

Project A
└── venv
    └── requests 2.28

Project B
└── venv
    └── requests 2.32

✅ Completely isolated

Create a Virtual Environment

Run the following command inside your project folder.

Terminal
python -m venv venv

Activate the Environment

Operating System Command
Windows (Command Prompt) venv\Scripts\activate
Windows (PowerShell) venv\Scripts\Activate.ps1
macOS / Linux source venv/bin/activate

Install Packages

After activating the virtual environment, install packages normally using pip.

Terminal
pip install requests

pip install pandas

pip install numpy

View Installed Packages

Terminal
pip list

Create requirements.txt

Save your project's dependencies so others can install the same package versions.

Terminal
pip freeze > requirements.txt

Install from requirements.txt

Terminal
pip install -r requirements.txt

Deactivate the Environment

Terminal
deactivate

Common Commands

Command Description
python -m venv venv Create a virtual environment.
activate Activate the environment.
pip install package Install a package.
pip list List installed packages.
pip freeze Export dependencies.
deactivate Exit the environment.

Quick Summary

Task Command
Create venv python -m venv venv
Activate activate
Install package pip install
Save dependencies pip freeze
Install dependencies pip install -r requirements.txt
Deactivate deactivate
Best Practice: Create a new virtual environment for every Python project. This keeps dependencies isolated, reproducible and easy to manage.
Common Mistake: Do not commit the venv folder to Git. Instead, add it to your .gitignore file and share a requirements.txt file so others can recreate the environment.
Interview Question: Why should every Python project have its own virtual environment?

Each project can use different package versions without conflicts. Virtual environments also make projects easier to share, reproduce and deploy.

BEST PRACTICES

Python Best Practices

Writing Python code that works is only the first step. Following best practices makes your code easier to read, maintain, debug and collaborate on with other developers.

Follow PEP 8

PEP 8 is the official Python style guide. Following it makes your code consistent and easier for others to understand.

Recommendation Example
Use 4 spaces for indentation ✅ Standard Python style
Maximum line length ≈ 88 characters (Black) or 79 (PEP 8)
Separate functions with blank lines Improves readability
Group imports at the top Standard practice

Use Meaningful Names

Choose descriptive names instead of short or unclear abbreviations.

❌ Poor ✅ Better
x user_count
d user_data
tmp total_price
calc() calculate_total()

Keep Functions Small

Each function should perform one clear task. Small functions are easier to understand, test and reuse.

Python
def calculate_total(price, tax):

    return price + tax

Use Constants

Store fixed values in uppercase variables instead of hardcoding them throughout your program.

Python
MAX_USERS = 100

TIMEOUT = 30

Avoid Global Variables

Instead of... Prefer...
Global state Function parameters
Shared mutable variables Return values
Implicit dependencies Explicit arguments

Write Docstrings

Document public functions, classes and modules so other developers understand their purpose.

Python
def add(a, b):

    """Return the sum of two numbers."""

    return a + b

Use Virtual Environments

Create a separate virtual environment for every project to avoid dependency conflicts.

Terminal
python -m venv venv

Prefer Logging Over print()

Use the logging module for debugging and production applications instead of relying on print().

Python
import logging

logging.basicConfig(level=logging.INFO)

logging.info("Application started")

Common Anti-Patterns

Avoid Prefer
Very long functions Split into smaller functions
Deep nesting Return early when possible
from module import * Explicit imports
Bare except: Specific exceptions
Magic numbers Named constants
Duplicated code Reusable functions

Python Best Practices Checklist

Practice Status
Follow PEP 8
Meaningful variable names
Small reusable functions
Use type hints
Write docstrings
Use virtual environments
Handle exceptions properly
Prefer logging
Best Practice: Write code for humans first and computers second. Clear, readable code is easier to maintain and often prevents bugs before they happen.
Interview Question: Why is following Python best practices important even if the code already works?

Well-structured code is easier to read, test, debug and extend. Following established conventions also makes collaboration with other developers much smoother and reduces long-term maintenance costs.

FAQ

Python Cheat Sheet FAQ

Find answers to the most common Python questions asked by beginners and experienced developers.

What is Python?

Python is a high-level, interpreted programming language known for its simple syntax, readability and versatility. It is widely used for web development, automation, data science, artificial intelligence, scripting and software development.

Is Python easy to learn?

Yes. Python's clean and readable syntax makes it one of the best programming languages for beginners.

What is the difference between a list and a tuple?

Lists are mutable, meaning they can be changed after creation. Tuples are immutable and cannot be modified once created.

When should I use a dictionary?

Use dictionaries whenever data is naturally represented as key-value pairs, such as user profiles, settings or configuration data.

What is a virtual environment?

A virtual environment creates an isolated Python installation for a project, preventing dependency conflicts between different projects.

What is PEP 8?

PEP 8 is the official Python style guide. It defines coding conventions that improve readability and maintainability.

What is pip?

pip is Python's package manager. It allows you to install, update and remove third-party libraries.

What is the difference between == and is?

== compares values, while is checks whether two variables reference the exact same object in memory.

Why should I use functions?

Functions reduce duplicated code, improve readability and make applications easier to maintain and test.

What are decorators used for?

Decorators extend the behavior of existing functions without modifying their original implementation. They are commonly used for logging, caching and authentication.

What is a generator?

A generator produces values one at a time using the yield keyword, making it more memory efficient than creating a full list.

What are type hints?

Type hints document the expected types of variables and functions. They improve IDE support and help detect bugs through static analysis.

Should I always use classes?

No. Use classes when objects share state and behavior. For simple scripts, functions are often a better choice.

What is exception handling?

Exception handling uses try, except, else and finally to gracefully handle runtime errors.

How do I install Python packages?

Use the command pip install package_name inside your virtual environment.

What is the difference between break and continue?

break immediately exits a loop, while continue skips the current iteration and continues with the next one.

What is __init__()?

__init__() is the constructor method that runs automatically when a new object is created.

Is Python good for AI and Machine Learning?

Yes. Python is the leading language for AI and machine learning thanks to libraries such as NumPy, Pandas, TensorFlow, PyTorch and scikit-learn.

Where can I download Python?

You can download the latest version from the official Python website at python.org.

Why use this Python Cheat Sheet?

This guide brings together the most important Python syntax, examples and best practices in one place, making it a quick reference for both beginners and experienced developers.

Leave a Comment