Python Cheat Sheet
# Python Cheat Sheet
## Data Types
```python
x = 42 # int
x = 3.14 # float
x = "hello" # str
x = True # bool
x = [1, 2, 3] # list
x = (1, 2, 3) # tuple
x = {1, 2, 3} # set
x = {"a": 1} # dict
x = None # NoneType
```
## List Comprehensions
```python
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
```
## String Methods
```python
"hello".upper() # "HELLO"
"Hello".lower() # "hello"
"a,b,c".split(",") # ["a", "b", "c"]
", ".join(["a","b"]) # "a, b"
"hello world".title() # "Hello World"
"hello".replace("l","r") # "herro"
```
## File I/O
```python
with open("file.txt", "r") as f:
content = f.read()
with open("file.txt", "w") as f:
f.write("data")
```
## Functions
```python
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Lambda
square = lambda x: x ** 2
```
## Classes
```python
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
```
## Error Handling
```python
try:
result = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
```
## Common Patterns
```python
# Map/Filter
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x*2, nums))
evens = list(filter(lambda x: x%2==0, nums))
# Dictionary merge
d1 = {"a": 1}
d2 = {"b": 2}
merged = {**d1, **d2}
```