Python Cheat Sheet
Quick reference for essential Python concepts
01
pip install — Package Management
pip install <package_name>— Install a packagepip install <package_name>==<version>— Install a specific versionpip install -r requirements.txt— Install from a requirements filepip uninstall <package_name>— Uninstall a packagepip list— List installed packagespip freeze > requirements.txt— Generate requirements.txt from current env
02
Virtual Environment Setup
python -m venv <env_name>— Create a new virtual environment- Windows (Activate):
.\<env_name>\Scripts\activate - macOS/Linux (Activate):
source <env_name>/bin/activate deactivate— Deactivate the current virtual environment
03
Command Line Inputs
Basic (sys.argv)
import sysscript_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) # optional
parser.add_argument('-v', '--verbose', action='store_true') # flag
args = parser.parse_args()
print(args.file)
print(args.count)
if args.verbose: print("Verbose mode on.")
04
Python Basics
Comments
# Single-line comment"""Multi-line comment"""
Variables & Data Types
name = "Alice"— Stringage = 30— Integerheight = 1.75— Floatis_student = True— Boolean
Operators
+ - * / %— Arithmetic== != < > <= >=— Comparisonand or not— Logical
Input / Output
print("Hello, World!")user_input = input("Enter your name: ")
Type Conversion
int("123")·str(45)·float("3.14")
05
Data Structures
Lists — Mutable, Ordered
my_list = [1, 2, 3, "a"]my_list.append(4)my_list[0]— access element ·my_list[1:3]— slicelen(my_list)
Tuples — Immutable, Ordered
my_tuple = (1, 2, "a")·my_tuple[0]
Dictionaries — Key-Value Pairs
my_dict = {"name": "Bob", "age": 25}my_dict["name"]·my_dict["city"] = "NY"my_dict.keys()·my_dict.values()·my_dict.items()
Sets — Unordered, Unique Elements
my_set = {1, 2, 3, 2}— results in{1, 2, 3}my_set.add(4)·my_set.remove(1)
06
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 loopcontinue— Skip current iteration, move to next
07
Functions
def greet(name):
return f"Hello, {name}!"
def add(a, b=0): # default parameter
return a + b
message = greet("Alice")sum_val = add(5)·sum_val = add(5, 3)
08
Object-Oriented Programming Basics
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy", "Golden Retriever")print(my_dog.name)·print(my_dog.bark())
09
File Handling
Reading
with open('myfile.txt', 'r') as f:
content = f.read()
# or: for line in f: print(line.strip())
Writing (overwrites)
with open('myfile.txt', 'w') as f:
f.write("Hello, file!\n")
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:
print(f"Unexpected error: {e}")
else:
print("No errors occurred.")
finally:
print("This always runs.")
11
List Comprehensions
squares = [x*x for x in range(5)]→[0, 1, 4, 9, 16]evens = [x for x in range(10) if x % 2 == 0]→[0, 2, 4, 6, 8]
12
String Formatting
- f-strings (3.6+):
f"Name: {name}, Age: {age}" - .format():
"Name: {}, Age: {}".format("Dan", 40) - Old style (%):
"Name: %s, Age: %d" % ("Dan", 40)