Python Cheat sheet 🐍
1. Data Types:
int_num = 42
float_num = 3.14
string_var = "Hello, Python!"
bool_var = True
2. Variables and Assignment:
x = 10
y = "Python"
3. Lists & Tuples:
my_list = [1, 2, 3, "Python"]
my_tuple = (1, 2, 3, "Tuple")
4. Dictionaries:
my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'}
5. Control flow:
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for item in my_list:
print(item)
while condition:
# code.
6. Functions:
def greet(name="User"):
return f"Hello, {name}!"
result = greet("John")
7. Classes & Objects:
class Dog:
def __init__(self, name):
[Link] = name
def bark(self):
print("Woof!")
my_dog = Dog("Buddy")
my_dog.bark()
8. File Handling:
with open("[Link]", "r") as file:
content = [Link]()
with open("new_file.txt", "w") as new_file:
new_file.write("Hello, Python!")
9. Exception Handling:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
10. Libraries & Modules:
import math
from datetime import datetime
result = [Link](25)
current_time = [Link]()
11. List Comprehensions:
squares = [x**2 for x in range(5)]
12. Lambda Functions:
add = lambda x, y: x + y
result = add(2, 3)
13. Virtual Environment:
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
source myenv/bin/activate # On Unix or MacOS
myenv\Scripts\activate # On Windows
# Deactivate the virtual environment
deactivate
14. Package Management:
# Install a package
pip install package_name
# List installed packages
pip list
# Create [Link]
pip freeze > [Link]
# Install packages from [Link]
pip install -r [Link]
15. Working with JSON:
import json
# Convert Python object to JSON
json_data = [Link]({"name": "John", "age": 25})
# Convert JSON to Python object
python_obj = [Link](json_data)
16. Regular Expression:
import re
pattern = r'\d+' # Match one or more digits
result = [Link](pattern, "There are 42 apples and 123 oranges.")
17. Working with Dates:
from datetime import datetime, timedelta
current_date = [Link]()
future_date = current_date + timedelta(days=7)
18. List Manipulations:
numbers = [1, 2, 3, 4, 5]
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Map
squared = list(map(lambda x: x**2, numbers))
# Reduce (requires functools)
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
19. Dictionary Manipulations:
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Get value with default
value = my_dict.get('d', 0)
# Dictionary comprehension
squared_dict = {key: value**2 for key, value in my_dict.items()}
20. Concurrency with Threading:
import threading
def print_numbers():
for i in range(5):
print(i)
thread = [Link](target=print_numbers)
[Link]()
21. Concurrency and Asyncio:
import asyncio
async def print_numbers():
for i in range(5):
print(i)
await [Link](1)
[Link](print_numbers())
22. Web Scraping with Beautiful Soap:
from bs4 import BeautifulSoup
import requests
url = "[Link]
response = [Link](url)
soup = BeautifulSoup([Link], '[Link]')
title = [Link]
23. RESTful API with Flask:
from flask import Flask, jsonify, request
app = Flask(__name__)
@[Link]('/api/data', methods=['GET'])
def get_data():
data = {'key': 'value'}
return jsonify(data)
if __name__ == '__main__':
[Link](debug=True)
24. Unit Testing with unittest:
import unittest
def add(x, y):
return x + y
class TestAddition([Link]):
def test_add_positive_numbers(self):
[Link](add(2, 3), 5)
if __name__ == '__main__':
[Link]()
25. Database Interaction with SQLite:
import sqlite3
conn = [Link]('[Link]')
cursor = [Link]()
# Execute SQL query
[Link]('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
# Commit changes
[Link]()
# Close connection
[Link]()
26. Python Decorators:
def decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@decorator
def my_function():
print("Inside the function")
my_function()
27. Working with Enums:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print([Link])
28. Working with Sets:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
union_set = set1 | set2
# Intersection
intersection_set = set1 & set2
# Difference
difference_set = set1 - set2
29. Sending Email with smtplib:
import smtplib
from [Link] import MIMEText
# Set up email server
server = [Link]('[Link]', 587)
[Link]()
# Log in to email account
[Link]('your_email@[Link]', 'your_password')
# Send email
msg = MIMEText('Hello, Python!')
msg['Subject'] = 'Python Email'
[Link]('your_email@[Link]', 'recipient@[Link]', msg.as_string())