Python Cheat Sheet
# PYTHON CHEAT SHEET
## 1. Basics
- Print: print("Hello World")
- Variables: x = 5, y = "Hello"
- Type: type(x)
- Input: name = input("Enter your name: ")
## 2. Data Types
- int, float, str, bool
- list, tuple, set, dict
- NoneType
## 3. Strings
- s = "Python"
- s.upper(), s.lower()
- s[0:3], len(s)
- s.replace("P", "J")
- f"Hello {name}"
## 4. Lists
- my_list = [1, 2, 3]
- my_list.append(4)
- my_list.remove(2)
- my_list[1:3]
- list comprehension: [x**2 for x in range(5)]
## 5. Tuples
- t = (1, 2, 3)
- Access: t[0]
## 6. Sets
- s = {1, 2, 3}
- s.add(4), s.remove(2)
- Union: s1 | s2, Intersection: s1 & s2
## 7. Dictionaries
- d = {"name": "John", "age": 25}
- d["name"], d.keys(), d.values()
## 8. Control Flow
- if, elif, else
- for i in range(5): print(i)
- while condition: ...
## 9. Functions
def greet(name="User"):
return f"Hello {name}"
## 10. Lambda & Map/Filter/Reduce
- square = lambda x: x*x
- list(map(lambda x: x*2, [1, 2, 3]))
## 11. Classes
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello {self.name}"
## 12. Exceptions
try:
x = 10 / 0
except ZeroDivisionError as e:
print(e)
finally:
print("Done")
## 13. File I/O
with open("file.txt", "w") as f:
f.write("Hello")
## 14. Modules & Packages
- import math
- from math import sqrt
## 15. Virtual Environments
python3 -m venv env
source env/bin/activate
## 16. Pip
pip install requests
## 17. Useful Built-ins
- zip(), enumerate(), sorted(), reversed()
## 18. List vs Generator
- [x**2 for x in range(1000)]
- (x**2 for x in range(1000))
## 19. Decorators
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
## 20. Async & Await
import asyncio
async def main():
await asyncio.sleep(1)
## 21. NumPy, Pandas (Data Science)
import numpy as np
import pandas as pd
## 22. Tips
- Pythonic way: Use list comprehensions and built-ins.