Ultimate Python Cheat Sheet Practical Python For Everyday Tasks
Ultimate Python Cheat Sheet Practical Python For Everyday Tasks
This Cheat Sheet was born out of necessity. Recently, I was tasked with
diving into a new Python project after some time away from the
language.
I’ve broken up the sections into logical areas that typically work
together so that you can jump to an area you are interested in and find
the most related items to that particular task or subject. This will
include file operations, API interactions, spreadsheet manipulation,
mathematical computations, and working with data structures like lists
and dictionaries. Additionally, I’ll highlight some useful libraries to
enhance your Python toolkit that are prevalent in the domains Python
is typically used.
1. Reading a File
2. Writing to a File
3. Appending to a File
9. Deleting a File
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
print('File deleted.')
else:
print('File does not exist.')
To read from and write to a file in binary mode (useful for images,
videos, etc.):
import requests
response = requests.get('https://api.example.com/data')
data = response.json() # Assuming the response is JSON
print(data)
import requests
response = requests.get('https://api.example.com/data')
try:
response.raise_for_status() # Raises an HTTPError if the status is 4xx,
5xx
data = response.json()
print(data)
except requests.exceptions.HTTPError as err:
print(f'HTTP Error: {err}')
import requests
try:
response = requests.get('https://api.example.com/data', timeout=5) #
Timeout in seconds
data = response.json()
print(data)
except requests.exceptions.Timeout:
print('The request timed out')
import requests
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get('https://api.example.com/protected', headers=headers)
data = response.json()
print(data)
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('https://api.example.com/submit', json=payload,
headers=headers)
print(response.json())
import requests
response = requests.get('https://api.example.com/data')
response.encoding = 'utf-8' # Set encoding to match the expected response
format
data = response.text
print(data)
import requests
with requests.Session() as session:
session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
response = session.get('https://api.example.com/data')
print(response.json())
9. Handling Redirects
import requests
response = requests.get('https://api.example.com/data',
allow_redirects=False)
print(response.status_code)
import requests
response = requests.get('https://api.example.com/large-data', stream=True)
for chunk in response.iter_content(chunk_size=1024):
process(chunk) # Replace 'process' with your actual processing function
1. Creating a List
To conjure a list into being:
2. Appending to a List
elements.append('Aether')
index_of_air = elements.index('Air')
7. List Slicing
8. List Comprehension
9. Sorting a List
elements.reverse()
1. Creating a Dictionary
3. Removing an Entry
if 'Helium' in elements:
print('Helium is present')
8. Dictionary Comprehension
9. Merging Dictionaries
import os
# Craft a path compatible with the underlying OS
path = os.path.join('mystic', 'forest', 'artifact.txt')
# Retrieve the tome's directory
directory = os.path.dirname(path)
# Unveil the artifact's name
artifact_name = os.path.basename(path)
import os
contents = os.listdir('enchanted_grove')
print(contents)
3. Creating Directories
import os
# create a single directory
os.mkdir('alchemy_lab')
# create a hierarchy of directories
os.makedirs('alchemy_lab/potions/elixirs')
import os
# remove a file
os.remove('unnecessary_scroll.txt')
# remove an empty directory
os.rmdir('abandoned_hut')
# remove a directory and its contents
import shutil
shutil.rmtree('cursed_cavern')
import subprocess
# Invoke the 'echo' incantation
result = subprocess.run(['echo', 'Revealing the arcane'],
capture_output=True, text=True)
print(result.stdout)
import os
# Read the 'PATH' variable
path = os.environ.get('PATH')
# Create a new environment variable
os.environ['MAGIC'] = 'Arcane'
import os
# Check if a path exists
exists = os.path.exists('mysterious_ruins')
# Ascertain if the path is a directory
is_directory = os.path.isdir('mysterious_ruins')
# Determine if the path is a file
is_file = os.path.isfile('ancient_manuscript.txt')
import tempfile
# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False)
print(temp_file.name)
# Erect a temporary directory
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
To unveil information about the host system, its name, and the
enchantments it supports:
import os
import platform
# Discover the operating system
os_name = os.name # 'posix', 'nt', 'java'
# Unearth detailed system information
system_info = platform.system() # 'Linux', 'Windows', 'Darwin'
2. Printing to STDOUT
3. Formatted Printing
name = "Merlin"
age = 300
print(f"{name}, of {age} years, speaks of forgotten lore.")
4. Reading Lines from STDIN
import sys
for line in sys.stdin:
print(f"Echo from the void: {line.strip()}")
5. Writing to STDERR
import sys
sys.stderr.write("Beware! The path is fraught with peril.\n")
6. Redirecting STDOUT
import sys
original_stdout = sys.stdout # Preserve the original STDOUT
with open('mystic_log.txt', 'w') as f:
sys.stdout = f # Redirect STDOUT to a file
print("This message is inscribed within the mystic_log.txt.")
sys.stdout = original_stdout # Restore STDOUT to its original glory
7. Redirecting STDERR
Redirecting STDERR:
import sys
with open('warnings.txt', 'w') as f:
sys.stderr = f # Redirect STDERR
print("This warning is sealed within warnings.txt.", file=sys.stderr)
import getpass
secret_spell = getpass.getpass("Whisper the secret spell: ")
import sys
# The script's name is the first argument, followed by those passed by the
invoker
script, first_arg, second_arg = sys.argv
print(f"Invoked with the sacred tokens: {first_arg} and {second_arg}")
import argparse
parser = argparse.ArgumentParser(description="Invoke the ancient scripts.")
parser.add_argument('spell', help="The spell to cast")
parser.add_argument('--power', type=int, help="The power level of the
spell")
args = parser.parse_args()
print(f"Casting {args.spell} with power {args.power}")
sum = 7 + 3 # Addition
difference = 7 - 3 # Subtraction
product = 7 * 3 # Multiplication
quotient = 7 / 3 # Division
remainder = 7 % 3 # Modulus (Remainder)
power = 7 ** 3 # Exponentiation
3. Mathematical Functions
4. Generating Permutations
5. Generating Combinations
import random
num = random.randint(1, 100) # Generate a random integer between 1 and 100
7. Working with Fractions
8. Statistical Functions
import statistics
data = [1, 2, 3, 4, 5]
mean = statistics.mean(data) # Average
median = statistics.median(data) # Median
stdev = statistics.stdev(data) # Standard Deviation
9. Trigonometric Functions
import math
angle_rad = math.radians(60) # Convert 60 degrees to radians
cosine = math.cos(angle_rad) # Cosine of the angle
1. Establishing a Connection
import psycopg2
connection = psycopg2.connect(
dbname='your_database',
user='your_username',
password='your_password',
host='your_host'
)
2. Creating a Cursor
cursor = connection.cursor()
3. Executing a Query
records = cursor.fetchall()
for record in records:
print(record)
5. Inserting Records
6. Updating Records
7. Deleting Records
8. Creating a Table
cursor.execute("""
CREATE TABLE your_new_table (
id SERIAL PRIMARY KEY,
column1 VARCHAR(255),
column2 INTEGER
)
""")
connection.commit()
9. Dropping a Table
To drop a table:
try:
cursor.execute("your first transactional query")
cursor.execute("your second transactional query")
connection.commit() # Commit if all is well
except Exception as e:
connection.rollback() # Rollback in case of any issue
print(f"An error occurred: {e}")
import asyncio
async def fetch_data():
print("Fetching data...")
await asyncio.sleep(2) # Simulate an I/O operation
print("Data retrieved.")
4. Creating Tasks
To dispatch tasks:
5. Asynchronous Iteration
8. Asynchronous Generators
9. Using Semaphores
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3. Sending Data
s.sendall(b'Hello, server')
4. Receiving Data
5. Closing a Socket
To gracefully close the socket, severing the network link:
s.close()
7. Accepting Connections
s.setblocking(False)
import socket
import netifaces
for interface in netifaces.interfaces():
addr = netifaces.ifaddresses(interface).get(netifaces.AF_INET)
if addr:
print(f"Interface: {interface}, Address: {addr[0]['addr']}")
1. Creating a DataFrame
import pandas as pd
data = {
'Element': ['Earth', 'Water', 'Fire', 'Air'],
'Symbol': ['🜃', '🜄', '🜂', '🜁']
}
df = pd.DataFrame(data)
df = pd.read_csv('elements.csv')
print(df.head())
4. Selecting Columns
symbols = df['Symbol']
5. Filtering Rows
To sift through the DataFrame, selecting rows that meet your criteria:
fire_elements = df[df['Element'] == 'Fire']
df['Length'] = df['Element'].apply(len)
To gather your data into groups and extract new data through
aggregation:
8. Merging DataFrames
To create an array:
import numpy as np
array = np.array([1, 2, 3, 4, 5])
5. Reshaping an Array
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum = a + b # Element-wise addition
difference = b - a # Element-wise subtraction
product = a * b # Element-wise multiplication
7. Matrix Multiplication
Basic dot product Operation:
9. Boolean Indexing
mean = np.mean(a)
maximum = np.max(a)
sum = np.sum(a)
To create names for axes and title your plot to give better context:
plt.plot(x, y)
plt.title('Growth Over Time')
plt.xlabel('Time')
plt.ylabel('Growth')
plt.show()
plt.scatter(x, y)
plt.show()
z = [2, 3, 4, 5, 6]
plt.plot(x, y)
plt.plot(x, z)
plt.show()
6. Creating Subplots
To create subplots:
7. Creating a Histogram
To create a histogram:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
plt.hist(data, bins=4)
plt.show()
8. Adding a Legend
To create a legend for the plot:
plt.plot(x, y, label='Growth')
plt.plot(x, z, label='Decay')
plt.legend()
plt.show()
9. Customizing Ticks
To create your own marks upon the axes, defining the scale of your
values:
plt.plot(x, y)
plt.xticks([1, 2, 3, 4, 5], ['One', 'Two', 'Three', 'Four', 'Five'])
plt.yticks([0, 5, 10, 15, 20, 25], ['0', '5', '10', '15', '20', '25+'])
plt.show()
plt.plot(x, y)
plt.savefig('growth_over_time.png')
1. Loading a Dataset
3. Training a Model
4. Making Predictions
predictions = model.predict(X_test)
6. Using Cross-Validation
To use Cross-Validation:
7. Feature Scaling
import joblib
# Saving the model
joblib.dump(model, 'model.joblib')
# Loading the model
loaded_model = joblib.load('model.joblib')
import plotly.graph_objs as go
import plotly.io as pio
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'))
pio.show(fig)
5. Creating a Histogram
To create a Histogram:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
fig = go.Figure(data=go.Histogram(x=data))
pio.show(fig)
data = [1, 2, 2, 3, 4, 4, 4, 5, 5, 6]
fig = go.Figure(data=go.Box(y=data))
pio.show(fig)
7. Creating Heatmaps
To create a heatmap:
import numpy as np
z = np.random.rand(10, 10) # Generate random data
fig = go.Figure(data=go.Heatmap(z=z))
pio.show(fig)
To create a subplot:
import pandas as pd
dates = pd.date_range('20230101', periods=5)
values = [10, 11, 12, 13, 14]
fig = go.Figure(data=go.Scatter(x=dates, y=values, mode='lines+markers'))
pio.show(fig)
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(f"Year: {year}, Month: {month}, Day: {day}, Hour: {hour}, Minute:
{minute}, Second: {second}")
weekday = now.strftime("%A")
print(f"Today is: {weekday}")
To converse with the ancient epochs, translating their count from the
dawn of Unix:
timestamp = datetime.timestamp(now)
print(f"Current timestamp: {timestamp}")
# Converting a timestamp back to a datetime
date_from_timestamp = datetime.fromtimestamp(timestamp)
print(f"Date from timestamp: {date_from_timestamp}")
import math
transformed = [math.sqrt(x) for x in range(1, 6)]
print(transformed) # Square roots of numbers from 1 to 5
1. Defining a Class
Creating a class:
class Wizard:
def __init__(self, name, power):
self.name = name
self.power = power
def cast_spell(self):
print(f"{self.name} casts a spell with power {self.power}!")
2. Creating an Instance
3. Invoking Methods
4. Inheritance
Subclassing:
class ArchWizard(Wizard):
def __init__(self, name, power, realm):
super().__init__(name, power)
self.realm = realm
def summon_familiar(self):
print(f"{self.name} summons a familiar from the {self.realm}
realm.")
5. Overriding Methods
class Sorcerer(Wizard):
def cast_spell(self):
print(f"{self.name} casts a powerful dark spell!")
6. Polymorphism
def unleash_magic(wizard):
wizard.cast_spell()
unleash_magic(merlin)
unleash_magic(Sorcerer("Voldemort", 90))
7. Encapsulation
class Alchemist:
def __init__(self, secret_ingredient):
self.__secret = secret_ingredient
def reveal_secret(self):
print(f"The secret ingredient is {self.__secret}")
8. Composition
class Spellbook:
def __init__(self, spells):
self.spells = spells
class Mage:
def __init__(self, name, spellbook):
self.name = name
self.spellbook = spellbook
To bind actions to the class itself or liberate them from the instance,
serving broader purposes:
class Enchanter:
@staticmethod
def enchant(item):
print(f"{item} is enchanted!")
@classmethod
def summon(cls):
print("A new enchanter is summoned.")
10. Properties and Setters
class Elementalist:
def __init__(self, element):
self._element = element
@property
def element(self):
return self._element
@element.setter
def element(self, value):
if value in ["Fire", "Water", "Earth", "Air"]:
self._element = value
else:
print("Invalid element!")
1. Basic Decorator
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before call")
result = func(*args, **kwargs)
print("After call")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello {name}")
greet("Alice")
3. Using functools.wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper function"""
return func(*args, **kwargs)
return wrapper
@my_decorator
def greet(name):
"""Greet someone"""
print(f"Hello {name}")
4. Class Decorator
@MyDecorator
def greet(name):
print(f"Hello {name}")
greet("Alice")
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello")
say_hello()
6. Method Decorator
class MyClass:
@method_decorator
def greet(self, name):
print(f"Hello {name}")
obj = MyClass()
obj.greet("Alice")
7. Stacking Decorators
@my_decorator
@repeat(2)
def greet(name):
print(f"Hello {name}")
greet("Alice")
def smart_decorator(arg=None):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if arg:
print(f"Argument: {arg}")
return func(*args, **kwargs)
return wrapper
if callable(arg):
return decorator(arg)
return decorator
@smart_decorator
def no_args():
print("No args")
@smart_decorator("With args")
def with_args():
print("With args")
no_args()
with_args()
class MyClass:
@classmethod
@my_decorator
def class_method(cls):
print("Class method called")
MyClass.class_method()
class MyClass:
@staticmethod
@my_decorator
def static_method():
print("Static method called")
MyClass.static_method()
Working With GraphQL
Executing a Query:
query = gql('''
{
allWizards {
id
name
power
}
}
''')
result = client.execute(query)
print(result)
query = gql('''
query GetWizards($element: String!) {
wizards(element: $element) {
id
name
}
}
''')
params = {"element": "Fire"}
result = client.execute(query, variable_values=params)
print(result)
4. Mutations
mutation = gql('''
mutation CreateWizard($name: String!, $element: String!) {
createWizard(name: $name, element: $element) {
wizard {
id
name
}
}
}
''')
params = {"name": "Gandalf", "element": "Light"}
result = client.execute(mutation, variable_values=params)
print(result)
5. Handling Errors
Error handling:
subscription = gql('''
subscription {
wizardUpdated {
id
name
power
}
}
''')
for result in client.subscribe(subscription):
print(result)
7. Fragments
query = gql('''
fragment WizardDetails on Wizard {
name
power
}
query {
allWizards {
...WizardDetails
}
}
''')
result = client.execute(query)
print(result)
8. Inline Fragments
9. Using Directives
query = gql('''
query GetWizards($withPower: Boolean!) {
allWizards {
name
power @include(if: $withPower)
}
}
''')
params = {"withPower": True}
result = client.execute(query, variable_values=params)
print(result)
transport =
RequestsHTTPTransport(url='https://your-graphql-endpoint.com/graphql',
use_json=True)
client = Client(transport=transport, fetch_schema_from_transport=True)
import re
text = "Search this string for patterns."
match = re.search(r"patterns", text)
if match:
print("Pattern found!")
pattern = re.compile(r"patterns")
match = pattern.search(text)
if re.match(r"^Search", text):
print("Starts with 'Search'")
if re.search(r"patterns.$", text):
print("Ends with 'patterns.'")
6. Splitting a String
9. Non-Capturing Groups
html = "<body><h1>Title</h1></body>"
match = re.search(r"<.*?>", html)
if match:
print(match.group()) # Matches '<body>'
pattern = re.compile(r"""
\b # Word boundary
\w+ # One or more word characters
\s # Space
""", re.VERBOSE)
match = pattern.search(text)
1. Concatenating Strings
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)
s = "Python"
print(s.upper()) # Uppercase
print(s.lower()) # Lowercase
print(s.title()) # Title Case
s = "filename.txt"
print(s.startswith("file")) # True
print(s.endswith(".txt")) # True
s = "split,this,string"
words = s.split(",") # Split string into list
joined = " ".join(words) # Join list into string
print(words)
print(joined)
s = "Hello world"
new_s = s.replace("world", "Python")
print(new_s)
s = "characters"
for char in s:
print(char) # Prints each character on a new line
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum())# True
s = "slice me"
sub = s[2:7] # From 3rd to 7th character
print(sub)
13. String Length with len
s = "length"
print(len(s)) # 6
path = r"C:\User\name\folder"
print(path)
url = 'https://example.com'
response = requests.get(url)
html = response.text
base_url = "https://example.com/page/"
for page in range(1, 6): # For 5 pages
page_url = base_url + str(page)
response = requests.get(page_url)
# Process each page's content
# Find the URL of the AJAX request (using browser's developer tools) and
fetch it
ajax_url = 'https://example.com/ajax_endpoint'
data = requests.get(ajax_url).json() # Assuming the response is JSON
9. Using Regular Expressions in Web Scraping
import re
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
html)
rp = RobotFileParser()
rp.set_url('https://example.com/robots.txt')
rp.read()
can_scrape = rp.can_fetch('*', url)
session = requests.Session()
session.get('https://example.com/login')
session.cookies.set('key', 'value') # Set cookies, if needed
response = session.get('https://example.com/protected_page')
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raises an error for bad status codes
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
import aiohttp
import asyncio
import csv
1. Installing a Package
pip list
3. Upgrading a Package
4. Uninstalling a Package
To uninstall a package:
Searching packages:
Requirements file:
# On Unix or MacOS
source venv/bin/activate
Understanding Dependencies:
import os
current_directory = os.getcwd() # Get the current working directory
import sys
sys.exit() # Exit the script
import math
result = math.sqrt(16) # Square root
import random
number = random.randint(1, 10) # Random integer between 1 and 10
import json
json_string = json.dumps({'name': 'Alice', 'age': 30}) # Dictionary to JSON
string
7. re - Regular Expressions
import re
match = re.search('Hello', 'Hello, world!') # Search for 'Hello' in the
string
import subprocess
subprocess.run(['ls', '-l']) # Run the 'ls -l' command
import threading
def worker():
print("Worker thread executing")
thread = threading.Thread(target=worker)
thread.start()
import logging
logging.warning('This is a warning message')
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
import itertools
for combination in itertools.combinations('ABCD', 2):
print(combination)
To hash data:
import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
import csv
with open('file.csv', mode='r') as infile:
reader = csv.reader(infile)
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
import sqlite3
conn = sqlite3.connect('example.db')
25. tkinter - GUI Toolkit
import tkinter as tk
root = tk.Tk()
import pickle
serialized_obj = pickle.dumps(obj)
import time
time.sleep(1) # Sleep for 1 second
29. calendar - General Calendar-related
Functions
import calendar
print(calendar.month(2023, 1)) # Print the calendar for January 2023
import shutil
shutil.copyfile('source.txt', 'dest.txt')
import tempfile
temp = tempfile.TemporaryFile()
import bz2
compressed = bz2.compress(b'your data here')
import gzip
with gzip.open('file.txt.gz', 'wt') as f:
f.write('your data here')
import ssl
ssl.wrap_socket(sock)
import imaplib
mail = imaplib.IMAP4_SSL('imap.example.com')
import smtplib
server = smtplib.SMTP('smtp.example.com', 587)
import base64
encoded_data = base64.b64encode(b'data to encode')
import difflib
diff = difflib.ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
'ore\ntree\nemu\n'.splitlines(keepends=True))
print(''.join(diff))
import gettext
gettext.install('myapp')
import secrets
secure_token = secrets.token_hex(16)
import uuid
unique_id = uuid.uuid4()
import html
escaped = html.escape('<a href="https://example.com">link</a>')
import tarfile
with tarfile.open('sample.tar.gz', 'w:gz') as tar:
tar.add('sample.txt')
Well, that’s all I have for now. I hope this list helps you get up to speed
fast. If you like it, please share or give it a like (it helps a lot!).
Thank you for reading until the end. Before you go: