Python Cheatsheet for Quick Reference

A comprehensive overview of core Python concepts.


Basics & Variables


Data Types & Typecasting

Data Type Example Description
int a = 10 Integer (Whole Number)
float n = 10.3 Floating Point (Decimal)
str s = "Student" String (Text)
bool t = True Boolean (True or False)

Type Conversion (Typecasting)


Operators

Arithmetic Operators

Operator Name Use
+ Addition / Concatenation Addition for int/float, Concatenation for str.
- Subtraction Subtraction.
* Multiplication / Repetition Multiplication for int/float, Repetition for str.
/ Division Returns a float result.
// Floor Division Returns the integer quotient (integer division).
% Modulus Returns the remainder after division.
** Exponentiation Power calculation.

Relational (Comparison) Operators

Compare two values and return True or False.

Logical Operators

Operator Description
and Returns True if both left and right sides are true.
or Returns False only if both left and right sides are false.
not Returns the negation of the given operand.

Shorthand (Assignment) Operators

Any operator with the = sign, e.g., +=, -=, *=, etc..

num = num + 7  # Same as...
num += 7
num = num * 2  # Same as...
num *= 2
				

Membership Operator


Strings

Escape Characters

Use a backslash (\) to insert illegal characters or special formatting.

String Methods

Method Description Example
lower() Converts a string into lower case. "Python".lower()"python"
upper() Converts a string into upper case. "Python".upper()"PYTHON"
capitalize() Converts the first character to upper case. "python".capitalize()"Python"
title() Converts the first char of each word to upper case. "py string".title()"Py String"
swapcase() Swaps cases (lower becomes upper, vice versa). "Py".swapcase()"pY"
strip() Returns a trimmed version of the string (removes leading/trailing whitespace or specified chars). "-Python-".strip('-')"Python"
replace(old, new) Returns a string where a specified value is replaced. "A B".replace('A', 'C')"C B"
index(x) Returns the index of the first occurrence of x. "python".index('t')2
count(x) Returns the number of times x occurs in the string. "Hello".count('l')2

String Test Methods (Boolean Return)


Formatted Printing

1. f-Strings (Recommended)

Prefix the string with f and embed expressions in curly braces {}.

x = 5; pi = 22/7
print(f"value of x is {x}") # Output: value of x is 5
print(f"value of pi is {pi:.3f}") # Output: value of pi is 3.143 (3 decimal places)
print(f"value of x is {x:5d}") # Output: value of x is     5 (width of 5 chars, right-aligned)
				

2. Modulo Operator (%) - (C-Style)

Use % followed by a format specifier (%d for int, %f for float).

x = 5; pi = 22/7
print("x = %d, pi = %f" % (x, pi)) # Output: x = 5, pi = 3.142857
print("x = %5d, pi = %.4f" % (x, pi)) # Output: x =     5, pi = 3.1429 (width 5 for x, 4 decimals for pi)
				

3. sep and end parameters in print()


Control Flow (if-elif-else)

Uses indentation to define code blocks.

if (condition):
    # Statement 1 (executed if condition is True)
elif (condition):
    # Statement 2 (optional, executed if previous conditions are False)
else:
    # Statement 3 (optional, executed if all previous conditions are False)
				

Single-Line Control Flow


Loops

A loop executes a block of statements repeatedly.

1. while Loop

Executes statements repeatedly until a given condition is satisfied. Used when the number of iterations is not known.

while condition:
    # body of while loop
    # increment/decrement counter (to avoid infinite loop)
				

2. for Loop

Used to iterate over sequences (string, list, tuple, dict, set) or any iterable object. Used when the number of iterations is known.

# For Each Loop
for var in iterable:
    # statements
    
# For Loop with range()
for var in range(start, stop, step):
    # statements
				

Loop Control Statements


Collections (Data Structures)

Collection Notation Mutability Order Duplicate Elements
List [ ] (Square Brackets) Mutable (Can be updated in place) Ordered Allowed
Tuple ( ) (Parentheses) Immutable (Cannot be changed in place) Ordered Allowed
Set { } (Curly Braces) or set() Mutable Unordered Not allowed (Unique items)
Dictionary {key: value} Mutable Unordered (Ordered in Python 3.7+) Keys: Not allowed. Values: Allowed.

List Methods & Functions

Dictionary Operations

Set Operations (with set1 = {1, 2, 3, 4}, set2 = {1, 3, 5})

Operation Expression Result
Union set1 | set2 {1, 2, 3, 4, 5}
Intersection set1 & set2 {1, 3}
Difference set1 - set2 {2, 4}
Symmetric Difference set1 ^ set2 {2, 4, 5}
Subset Check set1 <= set2 False

Comprehensions

List Comprehension (Mapping)

A concise way to create lists from existing iterables.

L = [f(x) for x in iterable]

# Example: Square of elements in L1
L1 = [1, 2, 3, 4]
L = [x**2 for x in L1] # L -> [1, 4, 9, 16]
				

List Comprehension (Filtering & Mapping)

Includes an if condition for filtering.

L = [f(x) for x in iterable if condition]

# Example: Only even elements of L1
L = [x for x in L1 if x % 2 == 0] # L -> [2, 4]
				

List Comprehension (if-else)

Includes a conditional expression using if-else (note its position at the start).

L = [f(x) if condition else g(x) for x in iterable]
				

Functions & Best Practices

Defining a Function

A reusable block of statements for a specific task.

def function_name(parameters): # Keyword, name, and parameters
    # Body of statements
    return expression # Returns a value (optional)
				

Arguments

Type Hinting (Industry Practice)

Though not strictly required by the Python interpreter, using type hints (: type -> type) is a best practice for clarity and static analysis.

# Defines a function taking a float and returning a float
def calculate_area(length: float, width: float) -> float:
    return length * width
				

Recursion

The process of calling a function within itself.

def factorial(n):
    if n == 0:  # Base Case
        return 1
    return n * factorial(n-1) # Recursive Case
				

Modules & Libraries

Ways to import libraries:

# 1. Imports entire library, requires "math." prefix
import math
print(math.sqrt(2))

# 2. Imports all contents, no prefix needed, generally discouraged
from math import *
print(sqrt(2))

# 3. Imports specific function, no prefix needed
from math import sqrt
print(sqrt(2))

# 4. Imports and renames the function
from math import sqrt as s
print(s(2))
				

File Handling (I/O)

Syntax to open a file: file = open(file_path, mode)

Important Modes

Mode Description
r Read operation. Throws error if file doesn't exist.
w Write operation. Overrides existing data or creates a new file.
a Append operation. Won't override existing data, adds to the end.
r+ Read and write. Does not override existing data.
w+ Write and read. Overwrites the file to zero length.
a+ Append and read. Won't override existing data.

Reading Methods

Writing Methods

File Pointer Control


Exception Handling (try-except)

Used to handle errors gracefully, allowing the program to continue execution instead of stopping abruptly.

try:
    # Code that may cause exception
except ExceptionType:
    # Code to run when a specific exception occurs
except:
    # Code to run for any other exception (generic)
else:
    # Code that runs ONLY IF no exception occurred in the 'try' block
finally:
    # Code that ALWAYS runs, regardless of whether an exception occurred or not
				

Common Exceptions

Raising an Exception

The raise statement forces a specific exception to occur.

if x > 3:
    raise Exception("Value is greater than 3")
				

🐍 The Python Help Function: Your Built-in Guide/Help for OPPE or in general programming

The built-in help() function is one of Python's most powerful tools. It provides interactive access to the documentation for modules, keywords, functions, classes, and methods. It works by reading the docstrings (documentation strings, written as """...""") that are built directly into the code.

1. Getting Help on Built-in Types (Classes)

You can get a full "manual page" for any built-in data type, like strings, lists, or dictionaries. This will show you the class description and a list of all its available methods.


# Get all information about the string class
help(str)

# Get all information about the list class
help(list)

# Get all information about the dictionary class
help(dict)
                

The output will list all methods, including "dunder" (double-underscore) methods like __init__ or __add__.

2. Getting Help on Specific Methods

If you don't want to read the entire manual, you can ask for help on one specific method. This is much faster and more focused.


# Get help just for the string's 'lower' method
help(str.lower)

# Get help just for the list's 'append' method
help(list.append)

# Get help for the dictionary's 'get' method
help(dict.get)
                

This will show you exactly what the method does, what arguments it takes, and what it returns.

3. Getting Help on Built-in Functions

You can get documentation for any of Python's built-in functions.


# Get help for the 'len' function
help(len)

# Get help for the 'print' function
# (This is useful for learning about 'sep' and 'end' arguments)
help(print)

# Get help for the 'range' function
help(range)
                

4. Getting Help on an Object (Instance)

This is a key concept for Object-Oriented Programming (OOP). You don't need to know the class of an object; you can just pass the object itself (the instance) to help().


# Create an instance of a list
my_list = [1, 2, 3]

# This will automatically detect it's a list and give you help(list)
help(my_list)

# Create an instance of a string
my_name = "Alice"

# This will give you help(str)
help(my_name)
                

5. Getting Help on Your Own Custom Classes (OOP)

The help() function will also work on your own classes and methods, if you write docstrings for them.


class Car:
    """
    A simple class to represent a Car.
    """
    def __init__(self, make, model):
        """Initializes a new Car instance."""
        self.make = make
        self.model = model
        
    def start_engine(self):
        """Prints a message to start the engine."""
        print(f"{self.make} {self.model}'s engine is running.")

# --- Now, let's use help() on our class ---

# 1. Get help on the CLASS itself
help(Car)

# 2. Get help on a METHOD of the class
help(Car.start_engine)

# 3. Get help on an INSTANCE of the class
my_car = Car("Tesla", "Model 3")
help(my_car)
                

Running help(Car) will neatly display all your custom docstrings, showing the class description and its methods. This is essential for writing code that others (and your future self) can understand.

Running help() in a Terminal

When you use help() in a command prompt or terminal (not in a notebook like Google Colab), it often opens a special viewer.

Tip: To exit this help viewer, simply press the q key on your keyboard.