Skip to content

Latest commit

 

History

History
384 lines (303 loc) · 7.03 KB

File metadata and controls

384 lines (303 loc) · 7.03 KB

Python Quick Reference Sheet 📚

A quick reference guide for common Python operations and syntax.

Variables & Types

# Basic types
name = "Alice"        # str
age = 25              # int
height = 5.8          # float
is_student = True     # bool
nothing = None        # NoneType

# Type conversion
str(42)               # "42"
int("42")             # 42
float("3.14")         # 3.14
bool(1)               # True

Strings

text = "Hello Python"

# Methods
text.upper()          # "HELLO PYTHON"
text.lower()          # "hello python"
text.strip()          # Remove whitespace
text.split(",")       # Split into list
", ".join(list)       # Join list into string
text.replace("old", "new")
text.find("substring")
text.startswith("He")
text.endswith("on")

# Formatting
f"Hello {name}"       # f-string (recommended)
"Hello {}".format(name)
"Hello %s" % name

# Slicing
text[0:5]             # "Hello"
text[::-1]            # Reverse

Lists

my_list = [1, 2, 3]

# Methods
my_list.append(4)
my_list.insert(0, 0)
my_list.remove(2)
my_list.pop()
my_list.index(3)
my_list.count(2)
my_list.sort()
my_list.reverse()
len(my_list)

# Accessing
my_list[0]            # First item
my_list[-1]           # Last item
my_list[1:3]          # Slice

# List comprehension
[x**2 for x in range(10)]
[x for x in range(10) if x % 2 == 0]

Dictionaries

my_dict = {"name": "Alice", "age": 25}

# Methods
my_dict["name"]       # Access
my_dict.get("name", "Default")
my_dict.keys()
my_dict.values()
my_dict.items()
my_dict.update({"city": "NYC"})
del my_dict["age"]
"name" in my_dict

# Iterating
for key, value in my_dict.items():
    print(key, value)

Tuples

my_tuple = (1, 2, 3)
# Immutable - cannot change after creation
# Use for: coordinates, fixed data, dictionary keys

Sets

my_set = {1, 2, 3}

# Methods
my_set.add(4)
my_set.remove(2)
my_set.discard(5)     # Safe remove
my_set.pop()

# Operations
set1 | set2           # Union
set1 & set2           # Intersection
set1 - set2           # Difference
set1 ^ set2           # Symmetric difference

Control Flow

# If/Else
if condition:
    do_something()
elif other_condition:
    do_other()
else:
    do_default()

# For loop
for item in iterable:
    process(item)

for i in range(10):
    print(i)

# While loop
while condition:
    do_something()

# Break/Continue
for item in items:
    if item == "skip":
        continue
    if item == "stop":
        break

Functions

# Basic
def function_name(param1, param2):
    return result

# Default values
def greet(name="Guest"):
    return f"Hello {name}"

# *args and **kwargs
def func(*args, **kwargs):
    pass

# Lambda
square = lambda x: x**2

# Type hints
def add(a: int, b: int) -> int:
    return a + b

Error Handling

try:
    risky_code()
except ValueError:
    handle_error()
except Exception as e:
    handle_any_error(e)
else:
    runs_if_no_error()
finally:
    always_runs()

File Operations

# Reading
with open("file.txt", "r") as f:
    content = f.read()
    lines = f.readlines()

# Writing
with open("file.txt", "w") as f:
    f.write("Hello")

# Appending
with open("file.txt", "a") as f:
    f.write("World")

Classes

class MyClass:
    def __init__(self, param):
        self.param = param
    
    def method(self):
        return self.param
    
    @staticmethod
    def static_method():
        pass

# Inheritance
class Child(Parent):
    def __init__(self):
        super().__init__()

Useful Built-in Functions

# Type checking
type(obj)
isinstance(obj, Class)
isinstance(obj, (int, float))

# Math
abs(-5)               # 5
max(1, 2, 3)          # 3
min(1, 2, 3)          # 1
sum([1, 2, 3])        # 6
round(3.14159, 2)     # 3.14

# Iteration
range(10)             # 0-9
range(1, 10)          # 1-9
range(1, 10, 2)        # 1, 3, 5, 7, 9

enumerate(items)      # (index, item) pairs
zip(list1, list2)     # Pairs items from lists

# Collections
len(collection)
sorted(collection)
reversed(collection)
any(iterable)         # True if any is True
all(iterable)         # True if all are True

# String/List operations
" ".join(list)
str.split(" ")
list(map(func, iterable))
list(filter(func, iterable))

List vs Tuple vs Set vs Dict

Feature List Tuple Set Dict
Ordered ✅ (3.7+)
Mutable
Indexed ✅ (by key)
Duplicates ❌ (keys)
Use Case Sequences Fixed data Unique items Key-value pairs

Common Patterns

# Check if empty
if not my_list:
    print("Empty")

# Default value
value = my_dict.get("key", "default")

# List of unique items
unique = list(set(my_list))

# Swap variables
a, b = b, a

# Multiple assignment
x, y, z = 1, 2, 3

# Unpacking
first, *rest = [1, 2, 3, 4]

# Conditional expression
result = "Yes" if condition else "No"

Import Statements

import module
from module import function
from module import function as alias
from module import *
import module as alias

Special Variables

__name__              # Module name or "__main__"
__file__              # Current file path
__doc__               # Module docstring

Comparison Operators

==                    # Equal
!=                    # Not equal
<                     # Less than
>                     # Greater than
<=                    # Less or equal
>=                    # Greater or equal
is                    # Identity (same object)
is not                # Not identity
in                    # Membership
not in                # Not membership

Logical Operators

and                   # Both must be True
or                    # At least one True
not                   # Negation

String Methods Quick Reference

Method Description
.upper() Convert to uppercase
.lower() Convert to lowercase
.strip() Remove whitespace
.split() Split into list
.join() Join list into string
.replace() Replace substring
.find() Find substring index
.startswith() Check prefix
.endswith() Check suffix
.isalpha() All alphabetic
.isdigit() All digits
.isalnum() Alphanumeric

File Modes

Mode Description
"r" Read (default)
"w" Write (overwrites)
"a" Append
"x" Exclusive creation
"b" Binary mode
"t" Text mode (default)
"+" Read and write

Common Exceptions

Exception When It Occurs
ValueError Wrong type of value
TypeError Wrong type used
IndexError List index out of range
KeyError Dictionary key not found
FileNotFoundError File doesn't exist
ZeroDivisionError Division by zero
NameError Variable not defined
AttributeError Attribute doesn't exist

Tip: Keep this reference handy while learning Python! 📖