Python Cheat Sheet v1.0

Fast, clean, and brewed just right. ☕

1. Virtual Environment Setup

python -m venv venv
source venv/bin/activate
deactivate
rm -rf venv

2. PIP Package Management

pip install package
pip uninstall package
pip install --upgrade package
pip freeze > requirements.txt
pip install -r requirements.txt

3. Core Data Structures

List: fruits = ['apple', 'banana']
Tuple: point = (3, 4)
Set: colors = {'red', 'green'}
Dict: user = {'name': 'Alice', 'age': 30}
String: greeting = "Hello"
Range: range(5)
Bytes: b'hello'
Bytearray: bytearray(b'hello')
Deque: deque([1, 2, 3])

4. Control Flow

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

for fruit in ['apple', 'banana']:
    print(fruit)

while x < 5:
    print(x)
    x += 1

for i in range(5):
    if i == 3:
        break
    if i == 2:
        continue
    print(i)

if True:
    pass

5. File I/O

with open('file.txt', 'r') as f:
    contents = f.read()

with open('file.txt', 'w') as f:
    f.write("Hello World")

with open('file.txt', 'a') as f:
    f.write("Another line")

with open('file.txt', 'r') as f:
    lines = f.readlines()

6. List Comprehensions

squares = [x*x for x in range(5)]
even_squares = [x*x for x in range(10) if x%2 == 0]
pairs = [(x, y) for x in [1,2] for y in [3,4]]

7. Functions

def greet():
    print("Hello!")

def add(a, b):
    return a + b

def greet(name="World"):
    print(f"Hello, {name}!")

def stats(x, y):
    return x+y, x*y

def add_all(*args):
    return sum(args)

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

double = lambda x: x * 2

8. Type Casting

int("5")
float("5.7")
str(5)
list((1, 2, 3))
tuple([1, 2, 3])
set([1, 2, 3])
dict([('a', 1), ('b', 2)])
list("hello")

def greet(name: str):
    print(f"Hello, {name}")

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

from typing import Union

def stringify(x: Union[int, float]) -> str:
    return str(x)

9. String Operations

"hello world".split()
" ".join(["hello", "world"])
"hello world".replace("world", "Python")
"hello".upper()
"HELLO".lower()
"hello".startswith("he")
"hello".endswith("lo")

10. Error Handling

try:
    1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

try:
    x = int(input("Enter number: "))
except ValueError:
    print("Invalid!")
else:
    print("Good input!")

try:
    file = open('file.txt')
finally:
    file.close()

raise ValueError("Wrong value!")

11. Classes and OOP Basics

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print("Woof!")

my_dog = Dog("Buddy")
my_dog.bark()

class Puppy(Dog):
    def bark(self):
        print("Yip!")

12. Quick Symbols and Syntax

== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal
<= Less or equal
+ Addition
- Subtraction
* Multiplication
** Power
/ Division
// Floor Division
% Modulo
: Start of block
[] Lists or indexing
() Tuples or calls
{} Dict or Set
# Comment
*args Positional arguments
**kwargs Keyword arguments

13. Common Built-in Functions

len([1,2,3])
sum([1,2,3])
min(4,2,8)
max(4,2,8)
sorted([3,1,2])
abs(-5)
round(3.1415, 2)
enumerate(['a', 'b'])
zip([1,2],[3,4])

14. Decorators (Basic Intro)

def my_decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

15. Context Managers (with)

with open('file.txt', 'r') as f:
    contents = f.read()

from contextlib import contextmanager

@contextmanager
def simple_cm():
    print("Entering")
    yield
    print("Exiting")

16. Useful Standard Libraries

import random
random.choice([1,2,3])

import math
math.sqrt(16)

from datetime import datetime
datetime.now()

from collections import Counter
Counter(['a', 'b', 'a'])

17. Comparison Operators

==  Equal to
!=  Not equal to
>   Greater than
<   Less than
>=  Greater or equal
<=  Less or equal
is  Same object
is not  Not same object
in  Membership
not in  Not membership