Python Cheatsheet
Essential Python syntax, built-in functions, and common operations
Useful Python Resources
Python Package Index (PyPI)
Repository of Python packages - find and install third-party libraries
Learn More →Basic Syntax
variable = valueVariable assignment
print(value)Output a value to the console
# This is a commentSingle line comment
"""Multi-line
comment"""Multi-line comment/docstring
if condition:
codeBasic if statement
for item in iterable:
codeFor loop syntax
while condition:
codeWhile loop syntax
def function_name(params):
return valueFunction definition
Data Types
str("text")String type
int(10)Integer type
float(10.5)Floating-point type
bool(True)Boolean type
list([1, 2, 3])List (mutable sequence)
tuple((1, 2, 3))Tuple (immutable sequence)
dict({"key": "value"})Dictionary (key-value pairs)
set({1, 2, 3})Set (unique unordered elements)
String Operations
str.upper()Convert string to uppercase
str.lower()Convert string to lowercase
str.strip()Remove whitespace from ends
str.split(delimiter)Split string into list
",".join(list)Join list elements with delimiter
str.replace(old, new)Replace substring in string
str.format()Format string with placeholders
f"Value: {variable}"F-string formatting (Python 3.6+)
List Operations
list.append(item)Add item to end of list
list.extend(iterable)Add items from iterable to list
list.insert(index, item)Insert item at position
list.remove(item)Remove first occurrence of item
list.pop([index])Remove and return item at index
list.sort()Sort list in place
list.reverse()Reverse list in place
list.copy()Create shallow copy of list
Dictionary Operations
dict.get(key, default)Get value with optional default
dict.keys()Get view of dictionary keys
dict.values()Get view of dictionary values
dict.items()Get view of dictionary key-value pairs
dict.update(other_dict)Update dictionary with elements from another
dict.pop(key[, default])Remove specified key and return value
dict.clear()Remove all items
dict.copy()Create shallow copy of dictionary
File Operations
with open(file, "r") as f:Open file for reading
with open(file, "w") as f:Open file for writing
f.read()Read entire file
f.readline()Read single line from file
f.readlines()Read all lines into list
f.write(string)Write string to file
f.writelines(list)Write list of strings to file
import jsonImport JSON module
Object-Oriented Programming
class ClassName:
passDefine a class
class Child(Parent):Class inheritance
def __init__(self):Constructor method
@classmethodClass method decorator
@staticmethodStatic method decorator
@propertyProperty decorator
super().__init__()Call parent class method
isinstance(obj, class)Check instance type
Exception Handling
try:
code
except Error:
handleBasic exception handling
raise Exception("message")Raise an exception
finally:Code that always executes
else:Code that runs if no exception
except (Error1, Error2):Catch multiple exceptions
except Error as e:Catch and use error object
assert condition, messageAssertion statement
with context_manager:Context manager protocol
Modules and Packages
import moduleImport a module
from module import nameImport specific name
from module import *Import all names (not recommended)
import module as aliasImport with alias
from . import moduleRelative import
pip install packageInstall package with pip
pip listList installed packages
pip freeze > requirements.txtSave dependencies list