Python Cheat Sheet
A comprehensive Python reference guide with syntax, examples, and usage instructions. Find the Python concepts, functions, and commands you need using the search bar or browse by category.
📚 Practice what you've learned with our Python Flashcards
Variables
Basic SyntaxAssign values to variables in Python
Syntax:
variable_name = valueExamples:
name = 'John' String variableage = 25 Integer variableprice = 19.99 Float variableis_active = True Boolean variableNotes:
Python is dynamically typed - no need to declare variable types
Comments
Basic SyntaxAdd comments to Python code
Syntax:
# Single line comment
'''Multi-line comment'''Examples:
# This is a single line comment Single line comment'''
This is a
multi-line comment
''' Multi-line comment using triple quotes"""Another way to write
multi-line comments""" Multi-line comment using double quotesNotes:
Use comments to explain your code and make it more readable
print()
Basic SyntaxOutput text to console
Syntax:
print(value1, value2, ...)Examples:
print('Hello, World!') Print a stringprint(42) Print a numberprint('Name:', name, 'Age:', age) Print multiple valuesprint(f'Hello {name}, you are {age} years old') Print with f-string formattingNotes:
print() automatically adds a newline. Use end='' to prevent this
input()
Basic SyntaxGet user input from console
Syntax:
input(prompt)Examples:
name = input('Enter your name: ') Get string inputage = int(input('Enter your age: ')) Get integer inputprice = float(input('Enter price: ')) Get float inputNotes:
input() always returns a string, convert to other types as needed
int
Data TypesInteger numbers in Python
Syntax:
int_var = numberExamples:
x = 42 Positive integery = -17 Negative integerz = int('123') Convert string to integerbinary = 0b1010 # 10 in decimal Binary literalNotes:
Python integers have unlimited precision
float
Data TypesFloating point numbers in Python
Syntax:
float_var = number.decimalExamples:
pi = 3.14159 Float literalscientific = 1.5e6 # 1,500,000 Scientific notationresult = float('3.14') Convert string to floatinfinity = float('inf') Represent infinityNotes:
Floats are double precision by default
str
Data TypesText strings in Python
Syntax:
'string' or "string" or '''multi-line'''Examples:
name = 'Alice' Single quotesmessage = "Hello World" Double quotesmultiline = '''Line 1
Line 2
Line 3''' Multi-line stringformatted = f'Hello {name}!' f-string formattingNotes:
Strings are immutable in Python
bool
Data TypesBoolean values True and False
Syntax:
bool_var = True/FalseExamples:
is_valid = True Boolean Trueis_empty = False Boolean Falseresult = bool(1) # True Convert to booleancheck = 5 > 3 # True Boolean from comparisonNotes:
Only True and False (capitalized) are boolean values
list
Data StructuresOrdered, mutable collection of items
Syntax:
my_list = [item1, item2, item3]Examples:
numbers = [1, 2, 3, 4, 5] List of integersfruits = ['apple', 'banana', 'cherry'] List of stringsmixed = [1, 'hello', True, 3.14] Mixed data typesempty = [] Empty listNotes:
Lists are ordered and allow duplicates. Use square brackets []
List Methods
Data StructuresCommon methods for list manipulation
Syntax:
list.method()Examples:
fruits.append('orange') Add item to endfruits.insert(1, 'grape') Insert at specific positionfruits.remove('banana') Remove first occurrenceitem = fruits.pop() Remove and return last itemNotes:
Lists are mutable - methods modify the original list
dict
Data StructuresKey-value pairs collection
Syntax:
my_dict = {'key1': 'value1', 'key2': 'value2'}Examples:
person = {'name': 'John', 'age': 30} Dictionary with string and int valuescolors = dict(red='#FF0000', blue='#0000FF') Dictionary using dict() constructorempty = {} Empty dictionarynested = {'person': {'name': 'Alice', 'age': 25}} Nested dictionaryNotes:
Dictionaries are unordered and keys must be immutable
tuple
Data StructuresOrdered, immutable collection of items
Syntax:
my_tuple = (item1, item2, item3)Examples:
coordinates = (10, 20) Tuple of coordinatescolors = ('red', 'green', 'blue') Tuple of stringssingle = (42,) Single item tuple (note the comma)empty = () Empty tupleNotes:
Tuples are immutable - cannot be changed after creation
set
Data StructuresUnordered collection of unique items
Syntax:
my_set = {item1, item2, item3}Examples:
unique_numbers = {1, 2, 3, 4, 5} Set of unique numbersletters = set('hello') # {'h', 'e', 'l', 'o'} Set from stringempty = set() Empty set (cannot use {})fruits = {'apple', 'banana', 'apple'} # duplicates removed Automatic duplicate removalNotes:
Sets automatically remove duplicates and are unordered
if/elif/else
Control FlowConditional statements for decision making
Syntax:
if condition:
# code
elif condition:
# code
else:
# codeExamples:
if age >= 18:
print('Adult') Simple if statementif score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C' if-elif-else chainif x > 0 and x < 100:
print('Valid range') Multiple conditions with 'and'result = 'positive' if x > 0 else 'non-positive' Ternary operatorNotes:
Python uses indentation to define code blocks - no braces needed
for loop
Control FlowIterate over sequences or ranges
Syntax:
for item in sequence:
# codeExamples:
for i in range(5):
print(i) Loop through range 0-4for fruit in fruits:
print(fruit) Loop through list itemsfor i, item in enumerate(fruits):
print(f'{i}: {item}') Loop with index using enumeratefor key, value in person.items():
print(f'{key}: {value}') Loop through dictionary itemsNotes:
for loops work with any iterable object
while loop
Control FlowRepeat code while condition is true
Syntax:
while condition:
# codeExamples:
count = 0
while count < 5:
print(count)
count += 1 Basic while loopwhile True:
user_input = input('Enter quit to exit: ')
if user_input == 'quit':
break Infinite loop with breakx = 10
while x > 0:
print(x)
x -= 1 Countdown loopNotes:
Be careful to avoid infinite loops - ensure the condition eventually becomes false
break/continue
Control FlowControl loop execution flow
Syntax:
break # exit loop
continue # skip to next iterationExamples:
for i in range(10):
if i == 5:
break
print(i) Break out of loop at i=5for i in range(10):
if i % 2 == 0:
continue
print(i) Skip even numbersfor i in range(3):
for j in range(3):
if j == 1:
break
print(i, j) Break only affects inner loopNotes:
break exits the loop completely, continue skips to next iteration
def
FunctionsDefine a function in Python
Syntax:
def function_name(parameters):
# code
return valueExamples:
def greet(name):
return f'Hello, {name}!' Simple function with parameterdef add(a, b):
return a + b Function with multiple parametersdef say_hello():
print('Hello!') Function with no parameters or returndef greet(name='World'):
return f'Hello, {name}!' Function with default parameterNotes:
Functions must be defined before they are called
lambda
FunctionsCreate anonymous functions
Syntax:
lambda parameters: expressionExamples:
square = lambda x: x**2 Lambda function to square a numberadd = lambda a, b: a + b Lambda function with multiple parametersnumbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) Using lambda with map()even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) Using lambda with filter()Notes:
Lambda functions are limited to single expressions
*args **kwargs
FunctionsVariable number of arguments
Syntax:
def func(*args, **kwargs):Examples:
def sum_all(*args):
return sum(args) Accept any number of positional argumentsdef print_info(**kwargs):
for key, value in kwargs.items():
print(f'{key}: {value}') Accept any number of keyword argumentsdef flexible_func(*args, **kwargs):
print('Args:', args)
print('Kwargs:', kwargs) Accept both *args and **kwargsflexible_func(1, 2, 3, name='Alice', age=30) Call with mixed argumentsNotes:
*args collects positional arguments, **kwargs collects keyword arguments
class
ClassesDefine a class in Python
Syntax:
class ClassName:
def __init__(self, parameters):
# constructorExamples:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age Basic class definitionclass Dog:
species = 'Canis lupus' # class variable
def __init__(self, name):
self.name = name # instance variable Class with class and instance variablesperson = Person('Alice', 30) Create an instance of the classNotes:
Use PascalCase for class names. __init__ is the constructor method
Class Methods
ClassesMethods inside a class
Syntax:
def method_name(self, parameters):
# codeExamples:
class Calculator:
def add(self, a, b):
return a + b Instance methodclass Person:
def __init__(self, name):
self.name = name
def introduce(self):
return f'Hi, I am {self.name}' Method using instance variableclass Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2 Method performing calculationNotes:
All instance methods must have 'self' as the first parameter
Inheritance
ClassesCreate a class that inherits from another
Syntax:
class ChildClass(ParentClass):Examples:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass Parent classclass Dog(Animal):
def speak(self):
return f'{self.name} says Woof!' Child class inheriting from Animalclass Cat(Animal):
def speak(self):
return f'{self.name} says Meow!' Another child classdog = Dog('Buddy')
print(dog.speak()) # Buddy says Woof! Using inherited classNotes:
Child classes inherit all methods and attributes from parent class
len()
Built-in FunctionsGet the length of a sequence
Syntax:
len(sequence)Examples:
len('hello') Length of string (5)len([1, 2, 3, 4]) Length of list (4)len({'a': 1, 'b': 2}) Length of dictionary (2)len((1, 2, 3)) Length of tuple (3)Notes:
Works with any sequence or collection type
type()
Built-in FunctionsGet the type of an object
Syntax:
type(object)Examples:
type(42) Returns <class 'int'>type('hello') Returns <class 'str'>type([1, 2, 3]) Returns <class 'list'>type(3.14) Returns <class 'float'>Notes:
Useful for debugging and type checking
range()
Built-in FunctionsGenerate a sequence of numbers
Syntax:
range(start, stop, step)Examples:
list(range(5)) [0, 1, 2, 3, 4] - stop onlylist(range(2, 8)) [2, 3, 4, 5, 6, 7] - start and stoplist(range(0, 10, 2)) [0, 2, 4, 6, 8] - with steplist(range(10, 0, -1)) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] - reverseNotes:
range() is commonly used in for loops
List Comprehension
ComprehensionsCreate lists using compact syntax
Syntax:
[expression for item in iterable if condition]Examples:
squares = [x**2 for x in range(5)] [0, 1, 4, 9, 16] - squares of 0-4evens = [x for x in range(10) if x % 2 == 0] [0, 2, 4, 6, 8] - even numberswords = ['hello', 'world', 'python']
lengths = [len(word) for word in words] [5, 5, 6] - lengths of wordsmatrix = [[i*j for j in range(3)] for i in range(3)] Nested comprehension for 2D matrixNotes:
More concise and often faster than traditional loops
Dictionary Comprehension
ComprehensionsCreate dictionaries using compact syntax
Syntax:
{key_expr: value_expr for item in iterable if condition}Examples:
squares = {x: x**2 for x in range(5)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}word_lengths = {word: len(word) for word in ['cat', 'dog', 'bird']} {'cat': 3, 'dog': 3, 'bird': 4}filtered = {k: v for k, v in original_dict.items() if v > 10} Filter dictionary by valuesNotes:
Useful for transforming existing dictionaries
try/except
Exception HandlingHandle errors gracefully
Syntax:
try:
# risky code
except ExceptionType:
# handle errorExamples:
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero') Handle specific exceptiontry:
age = int(input('Enter age: '))
except ValueError:
print('Please enter a valid number') Handle invalid inputtry:
file = open('data.txt')
except FileNotFoundError:
print('File not found')
finally:
print('This always runs') Using finally blockNotes:
Use specific exception types when possible, avoid bare except:
open()
File OperationsRead and write files
Syntax:
open(filename, mode)Examples:
with open('file.txt', 'r') as f:
content = f.read() Read entire filewith open('file.txt', 'w') as f:
f.write('Hello World') Write to filewith open('data.txt', 'r') as f:
lines = f.readlines() Read all lines into listwith open('log.txt', 'a') as f:
f.write('New log entry\n') Append to fileNotes:
Use 'with' statement for automatic file closing
os module
LibrariesOperating system interface
Syntax:
import osExamples:
import os
print(os.getcwd()) Get current working directoryos.listdir('.') List files in directoryos.path.exists('file.txt') Check if file existsos.makedirs('new_folder', exist_ok=True) Create directoryNotes:
Essential for file system operations
sys module
LibrariesSystem-specific parameters and functions
Syntax:
import sysExamples:
import sys
print(sys.version) Python version informationsys.argv Command line argumentssys.exit() Exit the programsys.path.append('/custom/path') Add to Python pathNotes:
Useful for system information and program control
json module
LibrariesJSON data handling
Syntax:
import jsonExamples:
import json
data = json.loads('{"name": "Alice", "age": 30}') Parse JSON stringjson_string = json.dumps({'name': 'Bob', 'age': 25}) Convert to JSON stringwith open('data.json', 'r') as f:
data = json.load(f) Load JSON from filewith open('output.json', 'w') as f:
json.dump(data, f, indent=2) Save JSON to fileNotes:
Essential for API communication and data storage
datetime module
LibrariesDate and time handling
Syntax:
import datetimeExamples:
from datetime import datetime
now = datetime.now() Current date and timebirthday = datetime(1990, 5, 15) Specific dateformatted = now.strftime('%Y-%m-%d %H:%M:%S') Format datetime as stringfrom datetime import timedelta
future = now + timedelta(days=30) Add time durationNotes:
Use for timestamps, scheduling, and time calculations
String Manipulation
String MethodsCommon string operations
Syntax:
string.method()Examples:
'hello world'.upper() 'HELLO WORLD' - convert to uppercase'PYTHON'.lower() 'python' - convert to lowercase' spaces '.strip() 'spaces' - remove whitespace'apple,banana,cherry'.split(',') ['apple', 'banana', 'cherry'] - split stringNotes:
Strings are immutable - methods return new strings
String Formatting
String MethodsFormat strings with variables
Syntax:
f'text {variable}' or 'text {}'.format(variable)Examples:
name = 'Alice'
f'Hello {name}!' f-string formatting (preferred)'Hello {}!'.format(name) .format() methodf'{3.14159:.2f}' '3.14' - format float to 2 decimalsf'{42:>5}' ' 42' - right-align in 5 charactersNotes:
f-strings (Python 3.6+) are the most readable and efficient
Python Programming Tips
Best Practices
- • Follow PEP 8 style guidelines for consistent, readable code
- • Use meaningful variable and function names that describe their purpose
- • Keep functions small and focused on a single task
- • Use list comprehensions for simple transformations and filtering
- • Handle exceptions appropriately with try/except blocks
Performance Tips
- • Use built-in functions and libraries - they're optimized in C
- • Choose appropriate data structures (list vs set vs dict)
- • Use generators for memory-efficient iteration over large datasets
- • Avoid global variables and prefer local scope when possible
- • Use f-strings for string formatting - they're fastest and most readable
Common Python Patterns
Pythonic Patterns
- • EAFP: Easier to Ask for Forgiveness than Permission
- • Duck Typing: "If it walks like a duck, it's a duck"
- • Context Managers: Use 'with' for resource management
- • Enumerate: Use enumerate() instead of range(len())
Data Processing
- • List Comprehensions: Concise data transformations
- • Generator Expressions: Memory-efficient processing
- • Zip Function: Combine multiple iterables
- • Map/Filter/Reduce: Functional programming approach
Learning Python
Getting Started
- • Install Python from python.org
- • Set up IDE (PyCharm, VS Code, or IDLE)
- • Learn basic syntax and data types
- • Practice with simple scripts
Intermediate Topics
- • Object-Oriented Programming
- • File handling and I/O operations
- • Error handling and debugging
- • Working with APIs and JSON
Advanced Topics
- • Decorators and metaclasses
- • Async programming with asyncio
- • Testing with unittest/pytest
- • Package management with pip
Quick Reference Guide
Data Types Reference
Basic Data Types
| Type | Example | Mutable | Description |
|---|---|---|---|
| int | 42 | No | Integer numbers |
| float | 3.14 | No | Floating point |
| str | 'hello' | No | Text strings |
| bool | True | No | Boolean values |
| list | [1, 2, 3] | Yes | Ordered collection |
| dict | {'a': 1} | Yes | Key-value pairs |
| tuple | (1, 2, 3) | No | Immutable sequence |
| set | {1, 2, 3} | Yes | Unique items |
Common Operations
type(obj) - Get object type
isinstance(obj, type) - Check if object is of type
int(), float(), str(), bool() - Convert types
list(), tuple(), set(), dict() - Convert collections
len(obj) - Get length of sequence/collection
sys.getsizeof(obj) - Get memory size
Common Built-in Functions
Data Processing
- •
len()- Get length - •
sum()- Sum numbers - •
min()- Find minimum - •
max()- Find maximum - •
sorted()- Sort sequence
Iteration
- •
range()- Generate numbers - •
enumerate()- Add indices - •
zip()- Combine sequences - •
map()- Apply function - •
filter()- Filter items
I/O & Utilities
- •
print()- Output text - •
input()- Get user input - •
open()- Open files - •
type()- Get object type - •
help()- Get documentation