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

36 concepts found
Filter by category:

Variables

Basic Syntax

Assign values to variables in Python

Syntax:

variable_name = value

Examples:

name = 'John'
String variable
age = 25
Integer variable
price = 19.99
Float variable
is_active = True
Boolean variable

Notes:

Python is dynamically typed - no need to declare variable types

Comments

Basic Syntax

Add 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 quotes

Notes:

Use comments to explain your code and make it more readable

print()

Basic Syntax

Output text to console

Syntax:

print(value1, value2, ...)

Examples:

print('Hello, World!')
Print a string
print(42)
Print a number
print('Name:', name, 'Age:', age)
Print multiple values
print(f'Hello {name}, you are {age} years old')
Print with f-string formatting

Notes:

print() automatically adds a newline. Use end='' to prevent this

input()

Basic Syntax

Get user input from console

Syntax:

input(prompt)

Examples:

name = input('Enter your name: ')
Get string input
age = int(input('Enter your age: '))
Get integer input
price = float(input('Enter price: '))
Get float input

Notes:

input() always returns a string, convert to other types as needed

int

Data Types

Integer numbers in Python

Syntax:

int_var = number

Examples:

x = 42
Positive integer
y = -17
Negative integer
z = int('123')
Convert string to integer
binary = 0b1010  # 10 in decimal
Binary literal

Notes:

Python integers have unlimited precision

float

Data Types

Floating point numbers in Python

Syntax:

float_var = number.decimal

Examples:

pi = 3.14159
Float literal
scientific = 1.5e6  # 1,500,000
Scientific notation
result = float('3.14')
Convert string to float
infinity = float('inf')
Represent infinity

Notes:

Floats are double precision by default

str

Data Types

Text strings in Python

Syntax:

'string' or "string" or '''multi-line'''

Examples:

name = 'Alice'
Single quotes
message = "Hello World"
Double quotes
multiline = '''Line 1
Line 2
Line 3'''
Multi-line string
formatted = f'Hello {name}!'
f-string formatting

Notes:

Strings are immutable in Python

bool

Data Types

Boolean values True and False

Syntax:

bool_var = True/False

Examples:

is_valid = True
Boolean True
is_empty = False
Boolean False
result = bool(1)  # True
Convert to boolean
check = 5 > 3  # True
Boolean from comparison

Notes:

Only True and False (capitalized) are boolean values

list

Data Structures

Ordered, mutable collection of items

Syntax:

my_list = [item1, item2, item3]

Examples:

numbers = [1, 2, 3, 4, 5]
List of integers
fruits = ['apple', 'banana', 'cherry']
List of strings
mixed = [1, 'hello', True, 3.14]
Mixed data types
empty = []
Empty list

Notes:

Lists are ordered and allow duplicates. Use square brackets []

List Methods

Data Structures

Common methods for list manipulation

Syntax:

list.method()

Examples:

fruits.append('orange')
Add item to end
fruits.insert(1, 'grape')
Insert at specific position
fruits.remove('banana')
Remove first occurrence
item = fruits.pop()
Remove and return last item

Notes:

Lists are mutable - methods modify the original list

dict

Data Structures

Key-value pairs collection

Syntax:

my_dict = {'key1': 'value1', 'key2': 'value2'}

Examples:

person = {'name': 'John', 'age': 30}
Dictionary with string and int values
colors = dict(red='#FF0000', blue='#0000FF')
Dictionary using dict() constructor
empty = {}
Empty dictionary
nested = {'person': {'name': 'Alice', 'age': 25}}
Nested dictionary

Notes:

Dictionaries are unordered and keys must be immutable

tuple

Data Structures

Ordered, immutable collection of items

Syntax:

my_tuple = (item1, item2, item3)

Examples:

coordinates = (10, 20)
Tuple of coordinates
colors = ('red', 'green', 'blue')
Tuple of strings
single = (42,)
Single item tuple (note the comma)
empty = ()
Empty tuple

Notes:

Tuples are immutable - cannot be changed after creation

set

Data Structures

Unordered collection of unique items

Syntax:

my_set = {item1, item2, item3}

Examples:

unique_numbers = {1, 2, 3, 4, 5}
Set of unique numbers
letters = set('hello')  # {'h', 'e', 'l', 'o'}
Set from string
empty = set()
Empty set (cannot use {})
fruits = {'apple', 'banana', 'apple'}  # duplicates removed
Automatic duplicate removal

Notes:

Sets automatically remove duplicates and are unordered

if/elif/else

Control Flow

Conditional statements for decision making

Syntax:

if condition:
    # code
elif condition:
    # code
else:
    # code

Examples:

if age >= 18:
    print('Adult')
Simple if statement
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
else:
    grade = 'C'
if-elif-else chain
if x > 0 and x < 100:
    print('Valid range')
Multiple conditions with 'and'
result = 'positive' if x > 0 else 'non-positive'
Ternary operator

Notes:

Python uses indentation to define code blocks - no braces needed

for loop

Control Flow

Iterate over sequences or ranges

Syntax:

for item in sequence:
    # code

Examples:

for i in range(5):
    print(i)
Loop through range 0-4
for fruit in fruits:
    print(fruit)
Loop through list items
for i, item in enumerate(fruits):
    print(f'{i}: {item}')
Loop with index using enumerate
for key, value in person.items():
    print(f'{key}: {value}')
Loop through dictionary items

Notes:

for loops work with any iterable object

while loop

Control Flow

Repeat code while condition is true

Syntax:

while condition:
    # code

Examples:

count = 0
while count < 5:
    print(count)
    count += 1
Basic while loop
while True:
    user_input = input('Enter quit to exit: ')
    if user_input == 'quit':
        break
Infinite loop with break
x = 10
while x > 0:
    print(x)
    x -= 1
Countdown loop

Notes:

Be careful to avoid infinite loops - ensure the condition eventually becomes false

break/continue

Control Flow

Control loop execution flow

Syntax:

break  # exit loop
continue  # skip to next iteration

Examples:

for i in range(10):
    if i == 5:
        break
    print(i)
Break out of loop at i=5
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
Skip even numbers
for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)
Break only affects inner loop

Notes:

break exits the loop completely, continue skips to next iteration

def

Functions

Define a function in Python

Syntax:

def function_name(parameters):
    # code
    return value

Examples:

def greet(name):
    return f'Hello, {name}!'
Simple function with parameter
def add(a, b):
    return a + b
Function with multiple parameters
def say_hello():
    print('Hello!')
Function with no parameters or return
def greet(name='World'):
    return f'Hello, {name}!'
Function with default parameter

Notes:

Functions must be defined before they are called

lambda

Functions

Create anonymous functions

Syntax:

lambda parameters: expression

Examples:

square = lambda x: x**2
Lambda function to square a number
add = lambda a, b: a + b
Lambda function with multiple parameters
numbers = [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

Functions

Variable number of arguments

Syntax:

def func(*args, **kwargs):

Examples:

def sum_all(*args):
    return sum(args)
Accept any number of positional arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f'{key}: {value}')
Accept any number of keyword arguments
def flexible_func(*args, **kwargs):
    print('Args:', args)
    print('Kwargs:', kwargs)
Accept both *args and **kwargs
flexible_func(1, 2, 3, name='Alice', age=30)
Call with mixed arguments

Notes:

*args collects positional arguments, **kwargs collects keyword arguments

class

Classes

Define a class in Python

Syntax:

class ClassName:
    def __init__(self, parameters):
        # constructor

Examples:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
Basic class definition
class Dog:
    species = 'Canis lupus'  # class variable
    
    def __init__(self, name):
        self.name = name  # instance variable
Class with class and instance variables
person = Person('Alice', 30)
Create an instance of the class

Notes:

Use PascalCase for class names. __init__ is the constructor method

Class Methods

Classes

Methods inside a class

Syntax:

def method_name(self, parameters):
    # code

Examples:

class Calculator:
    def add(self, a, b):
        return a + b
Instance method
class Person:
    def __init__(self, name):
        self.name = name
    
    def introduce(self):
        return f'Hi, I am {self.name}'
Method using instance variable
class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14159 * self.radius ** 2
Method performing calculation

Notes:

All instance methods must have 'self' as the first parameter

Inheritance

Classes

Create 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 class
class Dog(Animal):
    def speak(self):
        return f'{self.name} says Woof!'
Child class inheriting from Animal
class Cat(Animal):
    def speak(self):
        return f'{self.name} says Meow!'
Another child class
dog = Dog('Buddy')
print(dog.speak())  # Buddy says Woof!
Using inherited class

Notes:

Child classes inherit all methods and attributes from parent class

len()

Built-in Functions

Get 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 Functions

Get 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 Functions

Generate a sequence of numbers

Syntax:

range(start, stop, step)

Examples:

list(range(5))
[0, 1, 2, 3, 4] - stop only
list(range(2, 8))
[2, 3, 4, 5, 6, 7] - start and stop
list(range(0, 10, 2))
[0, 2, 4, 6, 8] - with step
list(range(10, 0, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] - reverse

Notes:

range() is commonly used in for loops

List Comprehension

Comprehensions

Create 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-4
evens = [x for x in range(10) if x % 2 == 0]
[0, 2, 4, 6, 8] - even numbers
words = ['hello', 'world', 'python']
lengths = [len(word) for word in words]
[5, 5, 6] - lengths of words
matrix = [[i*j for j in range(3)] for i in range(3)]
Nested comprehension for 2D matrix

Notes:

More concise and often faster than traditional loops

Dictionary Comprehension

Comprehensions

Create 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 values

Notes:

Useful for transforming existing dictionaries

try/except

Exception Handling

Handle errors gracefully

Syntax:

try:
    # risky code
except ExceptionType:
    # handle error

Examples:

try:
    result = 10 / 0
except ZeroDivisionError:
    print('Cannot divide by zero')
Handle specific exception
try:
    age = int(input('Enter age: '))
except ValueError:
    print('Please enter a valid number')
Handle invalid input
try:
    file = open('data.txt')
except FileNotFoundError:
    print('File not found')
finally:
    print('This always runs')
Using finally block

Notes:

Use specific exception types when possible, avoid bare except:

open()

File Operations

Read and write files

Syntax:

open(filename, mode)

Examples:

with open('file.txt', 'r') as f:
    content = f.read()
Read entire file
with open('file.txt', 'w') as f:
    f.write('Hello World')
Write to file
with open('data.txt', 'r') as f:
    lines = f.readlines()
Read all lines into list
with open('log.txt', 'a') as f:
    f.write('New log entry\n')
Append to file

Notes:

Use 'with' statement for automatic file closing

os module

Libraries

Operating system interface

Syntax:

import os

Examples:

import os
print(os.getcwd())
Get current working directory
os.listdir('.')
List files in directory
os.path.exists('file.txt')
Check if file exists
os.makedirs('new_folder', exist_ok=True)
Create directory

Notes:

Essential for file system operations

sys module

Libraries

System-specific parameters and functions

Syntax:

import sys

Examples:

import sys
print(sys.version)
Python version information
sys.argv
Command line arguments
sys.exit()
Exit the program
sys.path.append('/custom/path')
Add to Python path

Notes:

Useful for system information and program control

json module

Libraries

JSON data handling

Syntax:

import json

Examples:

import json
data = json.loads('{"name": "Alice", "age": 30}')
Parse JSON string
json_string = json.dumps({'name': 'Bob', 'age': 25})
Convert to JSON string
with open('data.json', 'r') as f:
    data = json.load(f)
Load JSON from file
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)
Save JSON to file

Notes:

Essential for API communication and data storage

datetime module

Libraries

Date and time handling

Syntax:

import datetime

Examples:

from datetime import datetime
now = datetime.now()
Current date and time
birthday = datetime(1990, 5, 15)
Specific date
formatted = now.strftime('%Y-%m-%d %H:%M:%S')
Format datetime as string
from datetime import timedelta
future = now + timedelta(days=30)
Add time duration

Notes:

Use for timestamps, scheduling, and time calculations

String Manipulation

String Methods

Common 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 string

Notes:

Strings are immutable - methods return new strings

String Formatting

String Methods

Format 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() method
f'{3.14159:.2f}'
'3.14' - format float to 2 decimals
f'{42:>5}'
' 42' - right-align in 5 characters

Notes:

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

TypeExampleMutableDescription
int42NoInteger numbers
float3.14NoFloating point
str'hello'NoText strings
boolTrueNoBoolean values
list[1, 2, 3]YesOrdered collection
dict{'a': 1}YesKey-value pairs
tuple(1, 2, 3)NoImmutable sequence
set{1, 2, 3}YesUnique items

Common Operations

Type Checking:

type(obj) - Get object type

isinstance(obj, type) - Check if object is of type

Type Conversion:

int(), float(), str(), bool() - Convert types

list(), tuple(), set(), dict() - Convert collections

Length and Size:

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

Operators Reference

Arithmetic

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
// (floor division)
% (modulo)
** (exponentiation)

Comparison

== (equal)
!= (not equal)
< (less than)
> (greater than)
<= (less or equal)
>= (greater or equal)
is (identity)

Logical

and (logical AND)
or (logical OR)
not (logical NOT)
in (membership)
not in (not member)