Python Cheatsheet for Quick Reference
A comprehensive overview of core Python concepts.
Table of Contents
Basics & Variables
- Print Output:
print("Hello World") - Input:
input()takes user input as a string. - Variables: Used to store values like numbers or text.
- Dynamic Typing: A variable's type is determined by the value it holds and can change.
- Multiple Assignment:
x, y, z = 1, "Hi", False - Delete Variable:
del xremoves the variable from memory.
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)
- Convert to Integer:
a = int(10.1)(converts10.1to10) - Convert to String:
c = str(10.3)(converts10.3to"10.3") - Boolean Conversion:
bool(0)isFalse. Any non-zero number or non-empty string isTrue. - Get Type:
type(value)returns the datatype of a variable or value.
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.
>: Greater than<: Less than>=: Greater than or equal<=: Less than or equal==: Equal!=: Not equal- Chaining: Use multiple relational operators together, e.g.,
print(1 < x < 6).
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
in: Checks if an item is inside or a part of another thing.print("IT" in " IIT Madras ") # Output: True
Strings
- Can be defined with single (
'Hello') or double quotes ("World"). - Indexing: Starts from 0.
s1[0]is the first character. Negative index-1is the last character. - Slicing:
s1[start:stop:step].s1[0:3]gives characters at indices 0, 1, 2. - Length:
len(s1)returns the number of characters. - Comparison: Based on alphabetical/dictionary order.
- Multiline Strings: Defined using triple quotes (
"""...""") (similar to multiline comments). - Immutability: Strings cannot be changed in place.
Escape Characters
Use a backslash (\) to insert illegal characters or special formatting.
\': Single quote (e.g.,print('It\'s Raining'))\n: Newline (cursor moves to the next line)\t: Tab (shifts cursor by 5 spaces)
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)
islower():Trueif all cased characters are lowercase.isupper():Trueif all cased characters are uppercase.istitle():Trueif the string follows title rules.isdigit():Trueif all characters are digits.isalpha():Trueif all characters are in the alphabet.isalnum():Trueif all characters are alphanumeric (a-z, A-Z, 0-9).startswith(x):Trueif the string starts withx.endswith(x):Trueif the string ends withx.
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()
sep: Specifies the separator between arguments (default is a space).print("11", "06", "24", sep="/") # Output: 11/06/24end: Specifies what to print after the statement (default is a newline\n).print("Hello", end = ", ") print("Python") # Output: Hello, Python
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
- If Statement:
if condition: blockif a % 2 == 0: print('even') - If-Else Statement (Ternary Operator):
block1 if condition else block2print('even') if a % 2 == 0 else print('odd')
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
range(stop): Generates numbers from0up tostop-1(step is1).range(start, stop): Generates numbers fromstartup tostop-1(step is1).range(start, stop, step): Generates numbers fromstartup tostop-1, increasing bystep.
Loop Control Statements
break: Terminates the current loop immediately.if condition: breakcontinue: Skips the remaining statements in the current iteration and forces execution of the next iteration.if condition: continuepass: Does nothing. Used when a statement is syntactically required but no code should execute (e.g., in empty loops, functions, or classes).if condition: pass
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
- Methods:
list.append(x),list.insert(i, x),list.extend(iterable),list.remove(x),list.pop(i)(removes and returns),list.sort(),list.reverse(). - Functions:
len(list),max(list),min(list),sum(list). sorted(list): Returns a new sorted list.- Slicing:
list[start:end:step] - Concatenation:
a + b - Deletion:
del a[i]ordel a[i:j]
Dictionary Operations
- Creation:
Dict = {}orDict = dict(). - Access:
Dict[key]orDict.get(key, default). - Add/Update:
Dict[new_key] = new_value(updates if key exists, adds otherwise). - Methods:
Dict.clear(),Dict.copy(),Dict.keys(),Dict.values(),Dict.items(),Dict.pop(key),Dict.popitem(),Dict.update(). - Keys must be Hashable: Immutable types like strings and tuples are valid keys.
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 |
- Methods:
set.add(x),set.remove(x)(raises error),set.discard(x)(no error if not found),set.pop()(removes random element). - Elements must be Hashable: Mutable objects (lists, dictionaries, sets) cannot be set elements.
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
- Positional Arguments: Values are assigned based on their position/order.
- Keyword Arguments: Caller specifies argument names with values, so order doesn't matter.
sub(x=30, y=10) # Keyword sub(10, 30) # Positional (results in 10-30 = -20) - Default Arguments: A parameter assumes a default value if not provided in the call.
def add(x, y=100): return x + y add(10) # Uses y=100, returns 110 - Multiple Returns: Functions can return multiple values separated by commas (returned as a tuple).
return x_squared, y_squared, z_squared
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.
- Base Case: The condition that stops the recursion (must return a value).
- Recursive Case: The part of the function that calls itself, working towards the base case.
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
file.read(): Extracts the entire content of the file as a single string.file.readline(): Reads a single line from the file and returns it as a string.file.readlines(): Reads all lines of the file and returns them as a list of strings.
Writing Methods
file.write(string): Writes the given string to the file (requires\nfor a new line).file.writelines(iterable): Writes a sequence of strings (e.g., a list of strings) to the file.
File Pointer Control
file.close(): Closes the file (good practice).file.tell(): Returns the current position of the File Handle (cursor).file.seek(offset, from_what): Changes the position of the File Handle.from_what=0: Start of the file (default)from_what=1: Current file positionfrom_what=2: End of the file
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
SyntaxError: Invalid code structure.TypeError: Operation applied to an object of the wrong type (e.g., adding string to int).NameError: Variable or function name not found in the current scope.IndexError: Index is out of range for a list/tuple.KeyError: Key not found in a dictionary.ZeroDivisionError: Attempt to divide a number by zero.FileNotFoundError: File not found when trying to open/access it.
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.