Ultimate Python Cheat Sheet: Practicals

This Cheat Sheet was born out of necessity. Recently, I was tasked with diving into a new Python project after some time away from language.
14 min read

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.

Ultimate Python Cheat Sheet: Practicals

I've always appreciated Python's practical syntax and form. However, being in Node/Typescript land for some time, I found myself in need of a rapid refresher on Python’s latest features, best practices, and most impactful tools. I needed to get back up to speed quickly without getting bogged down in the minutiae so I compiled this list so that I could reference the tasks and features I needed to use the most often. Essentially, to grasp the essential 20% of Python that addresses 80% of the programming needs I would encounter.

This guide is the culmination of that journey, offering a collection of the most practical Python knowledge, insights, and useful libraries that I encountered along the way. It’s designed to share my learning that I found most valuable, presented in a way that’s immediately applicable to your projects and challenges.

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.

Practical Python For Everyday Tasks

If you think I missed anything that should be included in the Cheat Sheet, please let me know in the comments and I'll update the list!

Working With Files

1. Reading a File

To read the entire content of a file:

with open('example.txt', 'r') as file:
  content = file.read()
  print(content)

2. Writing to a File

To write text to a file, overwriting existing content:

with open('example.txt', 'w') as file:
  file.write('Hello, Python!')

3. Appending to a File

To add text to the end of an existing file:

with open('example.txt', 'a') as file:
  file.write('\nAppend this line.')

4. Reading Lines into a List

To read a file line by line into a list:

with open('example.txt', 'r') as file:
  lines = file.readlines()
  print(lines)

5. Iterating Over Each Line in a File

To process each line in a file:

with open('example.txt', 'r') as file:
  for line in file:
  print(line.strip())

6. Checking If a File Exists

To check if a file exists before performing file operations:

import os
if os.path.exists('example.txt'):
  print('File exists.')
else:
  print('File does not exist.')

7. Writing Lists to a File

To write each element of a list to a new line in a file:

lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
  for line in lines:
      file.write(f'{line}\n')

8. Using With Blocks for Multiple Files

To work with multiple files simultaneously using with blocks:

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
  content = source.read()
  destination.write(content)

9. Deleting a File

To safely delete a file if it exists:

import os
if os.path.exists('example.txt'):
  os.remove('example.txt')
  print('File deleted.')
else:
  print('File does not exist.')

10. Reading and Writing Binary Files

To read from and write to a file in binary mode (useful for images, videos, etc.):

# Reading a binary file
with open('image.jpg', 'rb') as file:
  content = file.read()
# Writing to a binary file
with open('copy.jpg', 'wb') as file:
  file.write(content)

Working With Simple HTTP APIs

1. Basic GET Request

To fetch data from an API endpoint using a GET request:

  import requests
  response = requests.get('https://api.example.com/data')
  data = response.json()  # Assuming the response is JSON
  print(data)
  

2. GET Request with Query Parameters

To send a GET request with query parameters:

  import requests
  params = {'key1': 'value1', 'key2': 'value2'}
  response = requests.get('https://api.example.com/search', params=params)
  data = response.json()
  print(data)
  

3. Handling HTTP Errors

To handle possible HTTP errors gracefully:

  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}')
  

4. Setting Timeout for Requests

To set a timeout for API requests to avoid hanging indefinitely:

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

5. Using Headers in Requests

To include headers in your request (e.g., for authorization):

  import requests
  headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
  response = requests.get('https://api.example.com/protected', headers=headers)
  data = response.json()
  print(data)
  

6. POST Request with JSON Payload

To send data to an API endpoint using a POST request with a JSON payload:

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

7. Handling Response Encoding

To handle the response encoding properly:

  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)
  

8. Using Sessions with Requests

To use a session object for making multiple requests to the same host, which can improve performance:

  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

To handle or disable redirects in requests:

  import requests
  response = requests.get('https://api.example.com/data', allow_redirects=False)
  print(response.status_code)
  

10. Streaming Large Responses

To stream a large response to process it in chunks, rather than loading it all into memory:

  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
  

Working With Lists

1. Creating a List

To conjure a list into being:

# A list of mystical elements
 elements = ['Earth', 'Air', 'Fire', 'Water']

2. Appending to a List

To append a new element to the end of a list:

elements.append('Aether')

3. Inserting into a List

To insert an element at a specific position in the list:

# Insert 'Spirit' at index 1
elements.insert(1, 'Spirit')

4. Removing from a List

To remove an element by value from the list:

elements.remove('Earth')  # Removes the first occurrence of 'Earth'

5. Popping an Element from a List

To remove and return an element at a given index (default is the last item):

last_element = elements.pop()  # Removes and returns the last element

6. Finding the Index of an Element

To find the index of the first occurrence of an element:

index_of_air = elements.index('Air')

7. List Slicing

To slice a list, obtaining a sub-list:

# Get elements from index 1 to 3
sub_elements = elements[1:4]

8. List Comprehension

To create a new list by applying an expression to each element of an existing one:

# Create a new list with lengths of each element
lengths = [len(element) for element in elements]

9. Sorting a List

To sort a list in ascending order (in-place):

elements.sort()

10. Reversing a List

To reverse the elements of a list in-place:

elements.reverse()

Working With Dictionaries

1. Creating a Dictionary

To for give a new dictionary:

# A tome of elements and their symbols
elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li'}

2. Adding or Updating Entries

To add a new entry or update an existing one:

elements['Carbon'] = 'C'  # Adds 'Carbon' or updates its value to 'C'

3. Removing an Entry

To banish an entry from the dictionary:

del elements['Lithium']  # Removes the key 'Lithium' and its value

4. Checking for Key Existence

To check if a key resides within the dictionary:

if 'Helium' in elements:
  print('Helium is present')

5. Iterating Over Keys

To iterate over the keys in the dictionary:

for element in elements:
  print(element)  # Prints each key

6. Iterating Over Values

To traverse through the values in the dictionary:

for symbol in elements.values():
  print(symbol)  # Prints each value

7. Iterating Over Items

To journey through both keys and values together:

for element, symbol in elements.items():
  print(f'{element}: {symbol}')

8. Dictionary Comprehension

To conjure a new dictionary through an incantation over an iterable:

# Squares of numbers from 0 to 4
squares = {x: x**2 for x in range(5)}

9. Merging Dictionaries

To merge two or more dictionaries, forming a new alliance of their entries:

alchemists = {'Paracelsus': 'Mercury'}
philosophers = {'Plato': 'Aether'}
merged = {**alchemists, **philosophers}  # Python 3.5+
  

10. Getting a Value with Default

To retrieve a value safely, providing a default for absent keys:

element = elements.get('Neon', 'Unknown')  # Returns 'Unknown' if 'Neon' is not found


Working With The Operating System

1. Navigating File Paths

To craft and dissect paths, ensuring compatibility across realms (operating systems):

  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)
  

2. Listing Directory Contents

To reveal all entities within a mystical directory:

  import os
  contents = os.listdir('enchanted_grove')
  print(contents)
  

3. Creating Directories

To conjure new directories within the fabric of the filesystem:

  import os
  # create a single directory
  os.mkdir('alchemy_lab')
  # create a hierarchy of directories
  os.makedirs('alchemy_lab/potions/elixirs')
  

4. Removing Files and Directories

To erase files or directories, banishing their essence:

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

5. Executing Shell Commands

To invoke the shell's ancient powers directly from Python:

  import subprocess
  # Invoke the 'echo' incantation
  result = subprocess.run(['echo', 'Revealing the arcane'], capture_output=True, text=True)
  print(result.stdout)
  

6. Working with Environmental Variables

To read and write upon the ethereal environment variables:

  import os
  # Read the 'PATH' variable
  path = os.environ.get('PATH')
  # Create a new environment variable
  os.environ['MAGIC'] = 'Arcane'
  

7. Changing the Current Working Directory

To shift your presence to another directory within the filesystem:

  import os
  # Traverse to the 'arcane_library' directory
  os.chdir('arcane_library')
  

8. Path Existence and Type

To discern the existence of paths and their nature — be they file or directory:

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

9. Working with Temporary Files

To summon temporary files and directories, fleeting and ephemeral:

  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)
  

10. Getting System Information

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'
  


Working With CLI — STDIN, STDOUT, STDERR

1. Reading User Input

Getting input from STDIN:

user_input = input("Impart your wisdom: ")
print(f"You shared: {user_input}")

2. Printing to STDOUT

To print messages to the console:

print("Behold, the message of the ancients!")

3. Formatted Printing

To weave variables into your messages with grace and precision:

  name = "Merlin"
  age = 300
  print(f"{name}, of {age} years, speaks of forgotten lore.")
  

4. Reading Lines from STDIN

Trim whitespaces line by line from STDIN:

  import sys
  for line in sys.stdin:
  print(f"Echo from the void: {line.strip()}")

5. Writing to STDERR

To send message to STDERR:

  import sys
  sys.stderr.write("Beware! The path is fraught with peril.\n")

6. Redirecting STDOUT

To redirect the 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)

8. Prompting for Passwords

To prompt for passwords:

  import getpass
  secret_spell = getpass.getpass("Whisper the secret spell: ")

9. Command Line Arguments

Working with and parsing command line arguments:

  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}")
  

10. Using Argparse for Complex CLI Interactions

Adding descriptions and options/arguments:

  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}")
  


Working With Mathematical Operations and Permutations

1. Basic Arithmetic Operations

To perform basic arithmetic:

  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
  

2. Working with Complex Numbers

To work with complex numbers:

  z = complex(2, 3)  # Create a complex number 2 + 3j
  real_part = z.real  # Retrieve the real part
  imaginary_part = z.imag  # Retrieve the imaginary part
  conjugate = z.conjugate()  # Get the conjugate
  

3. Mathematical Functions

Common math functions:

  import math
  root = math.sqrt(16)  # Square root
  logarithm = math.log(100, 10)  # Logarithm base 10 of 100
  sine = math.sin(math.pi / 2)  # Sine of 90 degrees (in radians)
  

4. Generating Permutations

Easy way to generate permutations from a given set:

  from itertools import permutations
  paths = permutations([1, 2, 3])  # Generate all permutations of the list [1, 2, 3]
  for path in paths:
      print(path)
  

5. Generating Combinations

Easy way to generate combinations:

  from itertools import combinations
  combos = combinations([1, 2, 3, 4], 2)  # Generate all 2-element combinations
  for combo in combos:
      print(combo)
  

6. Random Number Generation

To get a random number:

  import random
  num = random.randint(1, 100)  # Generate a random integer between 1 and 100

7. Working with Fractions

When you need to work with fractions:

  from fractions import Fraction
  f = Fraction(3, 4)  # Create a fraction 3/4
  print(f + 1)  # Add a fraction and an integer
  

8. Statistical Functions

To get Average, Median, and Standard Deviation:

  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

To work with trigonometry:

  import math
  angle_rad = math.radians(60)  # Convert 60 degrees to radians
  cosine = math.cos(angle_rad)  # Cosine of the angle
  

10. Handling Infinity and NaN

To work with Infinity and NaN:

  import math
  infinity = math.inf  # Representing infinity
  not_a_number = math.nan  # Representing a non-number (NaN)
  


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!).

Thanks for reading and drop anything I missed in the comments!

You may like these posts

  • Extracting table data from PDF files can be a challenging task due to the complex nature of PDF documents. Unlike simple text extraction, tables require careful handlin…
  • 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 always appreciated …
  • Python is a versatile and powerful language for data science and software development. However, as data sets grow larger and computations become more complex, optimizing Pyt…
  • Python is the most sought-after skill in the programming domain. In this Python Interview Questions blog, I will introduce you to the most frequently asked questions in Pyth…
  •  A Python designer is an expert who spends significant time recorded as a hard copy server-side web application rationale utilizing the Python programming language. The…

Post a Comment

  1. Practical Python For Everyday Tasks
  2. Working With Files
    1. 1. Reading a File
    2. 2. Writing to a File
    3. 3. Appending to a File
    4. 4. Reading Lines into a List
    5. 5. Iterating Over Each Line in a File
    6. 6. Checking If a File Exists
    7. 7. Writing Lists to a File
    8. 8. Using With Blocks for Multiple Files
    9. 9. Deleting a File
    10. 10. Reading and Writing Binary Files
  3. Working With Simple HTTP APIs
    1. 1. Basic GET Request
    2. 2. GET Request with Query Parameters
    3. 3. Handling HTTP Errors
    4. 4. Setting Timeout for Requests
    5. 5. Using Headers in Requests
    6. 6. POST Request with JSON Payload
    7. 7. Handling Response Encoding
    8. 8. Using Sessions with Requests
    9. 9. Handling Redirects
    10. 10. Streaming Large Responses
  4. Working With Lists
    1. 1. Creating a List
    2. 2. Appending to a List
    3. 3. Inserting into a List
    4. 4. Removing from a List
    5. 5. Popping an Element from a List
    6. 6. Finding the Index of an Element
    7. 7. List Slicing
    8. 8. List Comprehension
    9. 9. Sorting a List
    10. 10. Reversing a List
  5. Working With Dictionaries
    1. 1. Creating a Dictionary
    2. 2. Adding or Updating Entries
    3. 3. Removing an Entry
    4. 4. Checking for Key Existence
    5. 5. Iterating Over Keys
    6. 6. Iterating Over Values
    7. 7. Iterating Over Items
    8. 8. Dictionary Comprehension
    9. 9. Merging Dictionaries
    10. 10. Getting a Value with Default
  6. Working With The Operating System
    1. 1. Navigating File Paths
    2. 2. Listing Directory Contents
    3. 3. Creating Directories
    4. 4. Removing Files and Directories
    5. 5. Executing Shell Commands
    6. 6. Working with Environmental Variables
    7. 7. Changing the Current Working Directory
    8. 8. Path Existence and Type
    9. 9. Working with Temporary Files
    10. 10. Getting System Information
  7. Working With CLI — STDIN, STDOUT, STDERR
    1. 1. Reading User Input
    2. 2. Printing to STDOUT
    3. 3. Formatted Printing
    4. 4. Reading Lines from STDIN
    5. 5. Writing to STDERR
    6. 6. Redirecting STDOUT
    7. 7. Redirecting STDERR
    8. 8. Prompting for Passwords
    9. 9. Command Line Arguments
    10. 10. Using Argparse for Complex CLI Interactions
  8. Working With Mathematical Operations and Permutations
    1. 1. Basic Arithmetic Operations
    2. 2. Working with Complex Numbers
    3. 3. Mathematical Functions
    4. 4. Generating Permutations
    5. 5. Generating Combinations
    6. 6. Random Number Generation
    7. 7. Working with Fractions
    8. 8. Statistical Functions
    9. 9. Trigonometric Functions
    10. 10. Handling Infinity and NaN