Python Cheatsheet

Deepak Ranolia
9 min readNov 18, 2023

--

This Python cheatsheet is designed to be your quick reference guide for Python programming. Whether you’re a beginner learning the basics or an experienced developer looking for a handy resource, this cheatsheet covers essential topics. Dive into the world of Python with confidence, using this cheatsheet to streamline your coding tasks and enhance your Python proficiency.

01 Data Types:
Python supports various data types such as integers, floats, strings, and booleans. Understanding these fundamental types is crucial for managing and manipulating data in your programs.

int_num = 42
float_num = 3.14
string_var = "Hello, Python!"
bool_var = True

02 Variables and Assignment:
Variables in Python are used to store data and can be assigned values using the equals sign (=). This enables the storage and reuse of values throughout your code.

x = 10
y = "Python"

03 Lists & Tuples:
Lists are mutable sequences that can hold a variety of data types, while tuples are immutable. These structures are essential for grouping related data and iterating through elements.

my_list = [1, 2, 3, "Python"]
my_tuple = (1, 2, 3, "Tuple")

04 Dictionaries:
Dictionaries store data in key-value pairs, allowing for fast retrieval of values based on unique keys. They are useful for organizing and accessing complex data efficiently.

my_dict = {'name': 'John', 'age': 25, 'city': 'Pythonville'}

05 Control Flow:
Statements like if, elif, else, for, and while enable conditional execution and iteration. These constructs help you control the execution path of your program based on various conditions.

if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for item in my_list:
print(item)
while condition:
# code

06 Functions:
Functions encapsulate reusable blocks of code and can accept parameters to perform specific tasks. Defining and calling functions enhance modularity and code reuse in your programs.

def greet(name="User"):
return f"Hello, {name}!"
result = greet("John")

07 Classes & Objects:
Classes define blueprints for objects, encapsulating data and behavior. Using object-oriented programming, you can model real-world entities and their interactions in your code.

class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof!")
my_dog = Dog("Buddy")
my_dog.bark()

08 File Handling:
Python provides easy-to-use functions for reading from and writing to files. This allows for data persistence and manipulation of file contents within your programs.

with open("file.txt", "r") as file:
content = file.read()
with open("new_file.txt", "w") as new_file:
new_file.write("Hello, Python!")

09 Exception Handling:
uses try, except, and finally blocks to manage errors gracefully. This helps ensure your program can handle unexpected situations and continue running.

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")

10 Libraries & Modules:
Python’s standard library and external modules extend its functionality. Importing and using libraries like math and datetime enable you to perform complex operations with minimal code.

import math
from datetime import datetime
result = math.sqrt(25)
current_time = datetime.now()

11 List Comprehensions:
provide a concise way to create lists. They are useful for generating new lists by applying an expression to each element of an iterable.

squares = [x**2 for x in range(5)]

12 Lambda Functions:
are anonymous functions defined with the lambda keyword. They are often used for small, throwaway functions without the need to formally define a function using def.

add = lambda x, y: x + y
result = add(2, 3)

13 Virtual Environment:
Virtual environments are isolated Python environments used to manage dependencies for different projects. They help prevent conflicts between dependencies by maintaining separate environments for each project.

# 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:
Package management in Python is typically handled using pip. It allows you to install, manage, and share packages and libraries required for your projects.

# Install a package
pip install package_name

# List installed packages
pip list

# Create requirements.txt
pip freeze > requirements.txt

# Install packages from requirements.txt
pip install -r requirements.txt

15 Working with JSON:
JSON (JavaScript Object Notation) is a lightweight data interchange format. Python provides the json module to encode and decode JSON data, making it easy to work with APIs and data storage.

import json

# Convert Python object to JSON
json_data = json.dumps({"name": "John", "age": 25})

# Convert JSON to Python object
python_obj = json.loads(json_data)

16 Regular Expressions:
Regular expressions (regex) are sequences of characters that define search patterns. The re module in Python allows you to match, search, and manipulate strings using regex.

import re
pattern = r'\d+' # Match one or more digits
result = re.findall(pattern, "There are 42 apples and 123 oranges.")

17 Working with Dates:
The datetime module in Python provides classes for manipulating dates and times. It allows you to perform operations such as getting the current date and time, adding or subtracting time, and formatting dates.

from datetime import datetime, timedelta

current_date = datetime.now()
future_date = current_date + timedelta(days=7)

18 List Manipulations:
Python offers several built-in functions to manipulate lists, such as filter, map, and reduce. These functions enable efficient data processing through functional programming techniques.

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:
Dictionaries in Python can be manipulated in various ways, such as accessing values with defaults and using dictionary comprehensions. These techniques enhance the flexibility and efficiency of handling key-value pairs.

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:
The threading module in Python allows you to create and manage threads for concurrent execution. It is useful for tasks that can be performed in parallel, improving the performance of your programs.

import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()

21 Concurrency with Asyncio:
The asyncio module provides a framework for writing asynchronous code using async and await syntax. It is suitable for I/O-bound and high-level structured network code.

import asyncio
async def print_numbers():
for i in range(5):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())

22 Web Scraping with Beautiful Soup:
Beautiful Soup is a Python library used for web scraping purposes. It allows you to parse HTML and XML documents and extract data from web pages.

from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.text

23 RESTful API with Flask:
Flask is a lightweight web framework for Python. It enables you to create RESTful APIs easily, allowing your applications to interact with other services over HTTP.

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/api/data', methods=['GET'])
def get_data():
data = {'key': 'value'}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)

24 Unit Testing with unittest:
The unittest module in Python provides a framework for creating and running unit tests. It helps ensure that your code works as expected by verifying individual units of functionality.

import unittest

def add(x, y):
return x + y
class TestAddition(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
if __name__ == '__main__':
unittest.main()

25 Database Interaction with SQLite:
SQLite is a lightweight, disk-based database. Python’s sqlite3 module allows you to interact with SQLite databases, performing operations such as executing SQL queries and managing database connections.

import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# Execute SQL query
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')

# Commit changes
conn.commit()

# Close connection
conn.close()

26 File Handling:
File handling in Python allows you to read from and write to files, making it essential for tasks involving data storage and retrieval.

# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()

27 Error Handling:
Error handling helps manage exceptions gracefully, ensuring your program can handle errors and unexpected situations without crashing.

try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected Error: {e}")
else:
print("No errors occurred.")
finally:
print("This block always executes.")

28 Working with JSON:
Working with JSON is crucial for data interchange between web services. Python’s json module makes it easy to convert between JSON and Python objects.

import json
data = {'name': 'John', 'age': 30}

# Convert Python object to JSON
json_data = json.dumps(data)

# Convert JSON to Python object
python_object = json.loads(json_data)

29 Python Decorators:
Python decorators allow you to modify the behavior of functions or methods. They are a powerful tool for code reuse and enhancing functionality.

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()

30 Working with Enums:
Enums in Python provide a way to define a set of named values, improving code readability and reliability by using symbolic names instead of literals.

from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)

31 Working with Sets:
Sets in Python are collections of unique elements. They support operations like union, intersection, and difference, making them useful for mathematical set operations.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
union_set = set1 | set2

# Intersection
intersection_set = set1 & set2

# Difference
difference_set = set1 - set2

32 List Comprehensions:
List comprehensions provide a concise way to create lists. They are efficient and often more readable than traditional loop-based constructions.

numbers = [1, 2, 3, 4, 5]

# Squares of even numbers
squares = [x**2 for x in numbers if x % 2 == 0]

33 Lambda Functions:
Lambda functions are small, anonymous functions defined using the lambda keyword. They are useful for quick, throwaway operations.

add = lambda x, y: x + y
result = add(3, 5)

34 Threading with Concurrent.futures:
Threading with Concurrent.futures allows for parallel execution of tasks, improving the performance of I/O-bound and CPU-bound operations.

from concurrent.futures import ThreadPoolExecutor
def square(x):
return x**2
with ThreadPoolExecutor() as executor:
results = executor.map(square, [1, 2, 3, 4, 5])

35 Internationalization (i18n) with gettext:
Internationalization (i18n) involves adapting software for different languages and regions. The gettext module facilitates translating and localizing your application.

import gettext

# Set language
lang = 'en_US'
_ = gettext.translation('messages', localedir='locale', languages=[lang]).gettext
print(_("Hello, World!"))

36 Virtual Environment:
Virtual environments create isolated spaces for dependencies, ensuring projects have their own unique settings and dependencies without conflicts.

# Create a virtual environment
python -m venv myenv

# Activate virtual environment
source myenv/bin/activate # On Unix/Linux
myenv\Scripts\activate # On Windows

# Deactivate virtual environment
deactivate

37 Working with Dates:
Working with dates in Python involves using the datetime module to manipulate date and time data, enabling tasks like formatting dates and calculating future or past dates.

from datetime import datetime, timedelta
now = datetime.now()

# Format date
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')

# Add days to a date
future_date = now + timedelta(days=7)

38 Working with Dictionaries:
Dictionaries in Python store key-value pairs, offering a fast way to retrieve and manipulate data. They are essential for mapping and associative arrays.

my_dict = {'name': 'John', 'age': 30}

# Get value with default
age = my_dict.get('age', 25)

# Iterate over keys and values
for key, value in my_dict.items():
print(f"{key}: {value}")

39 Regular Expressions:
Regular expressions (regex) are patterns used to match character combinations in strings. They are powerful tools for searching, replacing, and parsing text.

import re
text = "Hello, 123 World!"

# Match numbers
numbers = re.findall(r'\d+', text)

40 Working with Generators:
Generators in Python are functions that return an iterable set of items, one at a time, using the yield keyword. They are memory efficient and useful for large data sets.

def square_numbers(n):
for i in range(n):
yield i**2
squares = square_numbers(5)

41 Database Interaction with SQLite:
SQLite is a C library that provides a lightweight, disk-based database. Python’s sqlite3 module allows for easy integration and manipulation of SQLite databases.

import sqlite3

# Connect to SQLite database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()

# Execute SQL query
cursor.execute('SELECT * FROM mytable')

42 Working with ZIP Files:
ZIP files are used to compress files and directories. Python’s zipfile module enables creating, reading, writing, and extracting ZIP files.

import zipfile
with zipfile.ZipFile('archive.zip', 'w') as myzip:
myzip.write('file.txt')
with zipfile.ZipFile('archive.zip', 'r') as myzip:
myzip.extractall('extracted')

43 Web Scraping with requests and BeautifulSoup:
Web scraping involves extracting data from websites. The requests and BeautifulSoup libraries in Python simplify the process of fetching and parsing HTML content.

import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Extract data from HTML
title = soup.title.text

44 Sending Email with smtplib:
Sending email in Python can be done using the smtplib library, which supports SMTP protocol for sending mail with various configurations and MIME types.

import smtplib
from email.mime.text import MIMEText

# Set up email server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()

# Log in to email account
server.login('your_email@gmail.com', 'your_password')

# Send email
msg = MIMEText('Hello, Python!')
msg['Subject'] = 'Python Email'
server.sendmail('your_email@gmail.com', 'recipient@example.com', msg.as_string())

45 Working with JSON Files:
Working with JSON files involves using the json module to read and write JSON data to and from files. This is essential for data storage and interchange in web applications.

import json
data = {'name': 'John', 'age': 30}

# Write to JSON file
with open('data.json', 'w') as json_file:
json.dump(data, json_file)

# Read from JSON file
with open('data.json', 'r') as json_file:
loaded_data = json.load(json_file)

--

--

Deepak Ranolia
Deepak Ranolia

Written by Deepak Ranolia

Strong technical skills, such as Coding, Software Engineering, Product Management & Finance. Talk about finance, technology & life https://rb.gy/9tod91

Responses (9)