Python Cheat Sheet

Quick reference for essential Python concepts

1. pip install (Package Management)

  • `pip install `: Install a package.
  • `pip install ==`: Install a specific version.
  • `pip install -r requirements.txt`: Install packages from a requirements file.
  • `pip uninstall `: Uninstall a package.
  • `pip list`: List installed packages.
  • `pip freeze > requirements.txt`: Generate `requirements.txt` from current environment.

2. Virtual Environment Setup

  • `python -m venv `: Create a new virtual environment. (e.g., `python -m venv myenv`)
  • **Windows (Activate):** `.\\Scripts\activate`
  • **macOS/Linux (Activate):** `source /bin/activate`
  • `deactivate`: Deactivate the current virtual environment.

3. Command Line Inputs (`sys.argv` & `argparse`)

Basic (`sys.argv`):

  • `import sys`
  • `script_name = sys.argv[0]`
  • `first_arg = sys.argv[1]`
  • `all_args = sys.argv[1:]` (list of arguments)

Advanced (`argparse`):

import argparse

parser = argparse.ArgumentParser(description="My script.")
parser.add_argument('file', help='Input file path') # positional
parser.add_argument('--count', type=int, default=1, help='Number of times') # optional
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output') # flag
args = parser.parse_args()

print(args.file)
print(args.count)
if args.verbose: print("Verbose mode on.")

4. Python Basics

Comments:

  • `# Single-line comment`
  • `"""Multi-line comment"""`

Variables & Data Types:

  • `name = "Alice"` (String)
  • `age = 30` (Integer)
  • `height = 1.75` (Float)
  • `is_student = True` (Boolean)

Operators:

  • `+`, `-`, `*`, `/`, `%` (Arithmetic)
  • `==`, `!=`, `<`, `>`, `<=`, `>=` (Comparison)
  • `and`, `or`, `not` (Logical)

Input/Output:

  • `print("Hello, World!")`
  • `user_input = input("Enter your name: ")`

Type Conversion:

  • `int("123")`
  • `str(45)`
  • `float("3.14")`

5. Data Structures

Lists (Mutable, Ordered):

  • `my_list = [1, 2, 3, "a"]`
  • `my_list.append(4)`
  • `my_list[0]` (access element)
  • `my_list[1:3]` (slice)
  • `len(my_list)`

Tuples (Immutable, Ordered):

  • `my_tuple = (1, 2, "a")`
  • `my_tuple[0]`

Dictionaries (Mutable, Unordered, Key-Value Pairs):

  • `my_dict = {"name": "Bob", "age": 25}`
  • `my_dict["name"]`
  • `my_dict["city"] = "New York"`
  • `my_dict.keys()`
  • `my_dict.values()`
  • `my_dict.items()`

Sets (Mutable, Unordered, Unique Elements):

  • `my_set = {1, 2, 3, 2}` (results in `{1, 2, 3}`)
  • `my_set.add(4)`
  • `my_set.remove(1)`

6. Control Flow

`if/elif/else`:

if condition1:
    # code
elif condition2:
    # code
else:
    # code

`for` loops:

for item in iterable:
    # code
for i in range(5): # 0, 1, 2, 3, 4
    # code

`while` loops:

while condition:
    # code
    # remember to change condition to avoid infinite loop
  • `break`: Exit a loop.
  • `continue`: Skip current iteration, move to next.

7. Functions

Definition:

def greet(name):
    return f"Hello, {name}!"

def add(a, b=0): # Default parameter
    return a + b

Calling:

  • `message = greet("Alice")`
  • `sum_val = add(5)`
  • `sum_val = add(5, 3)`

8. Object-Oriented Programming (OOP) Basics

Class Definition:

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

    def bark(self):
        return f"{self.name} says Woof!"

Object Creation:

  • `my_dog = Dog("Buddy", "Golden Retriever")`
  • `print(my_dog.name)`
  • `print(my_dog.bark())`

9. File Handling

Reading:

with open('myfile.txt', 'r') as f:
    content = f.read()
    # or line by line:
    # for line in f:
    #     print(line.strip())

Writing (overwrites):

with open('myfile.txt', 'w') as f:
    f.write("Hello, file!\n")
    f.write("This is a new line.")

Appending:

with open('myfile.txt', 'a') as f:
    f.write("Appended line.\n")

10. Error Handling (`try/except`)

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError as e:
    print(f"Value Error: {e}")
except Exception as e: # Catch any other error
    print(f"An unexpected error occurred: {e}")
else:
    print("No errors occurred.")
finally:
    print("This always runs.")

11. List Comprehensions (Concise List Creation)

  • `squares = [x*x for x in range(5)]` # `[0, 1, 4, 9, 16]`
  • `even_numbers = [x for x in range(10) if x % 2 == 0]` # `[0, 2, 4, 6, 8]`

12. String Formatting

  • **f-strings (Python 3.6+):** `name = "Dan"; age = 40; print(f"Name: {name}, Age: {age}")`
  • **`.format()`:** `print("Name: {}, Age: {}".format("Dan", 40))`
  • **Old style (`%`):** `print("Name: %s, Age: %d" % ("Dan", 40))`