10 Simple Python Snippets for Web Development, Automation, and Data Science
TL;DR- A quick list of 10 modules and snippets that I use in a bunch of my Python programs, allowing me to automate complicated tasks and format my code just the way I like it.

Introduction
Python is one of my favorite coding tools, and it has tons of useful features as a ‘high-level’ programming language. High level languages usually automate a bunch of different functions natively, meaning you can essentially do the same thing in 5 lines of Python as 50 lines of Java.
For that reason, many developers use it to build even more productive functions and capabilities, here are a few that I’ve used to enhance my productivity and automate tasks →
Note: All code has been tested and currently works with Python 3.11 as of 12/2/22, feel free to comment if anything stops working or to suggest more tips!
Password Generator
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print(password)Programmatic Google Search
from googlesearch import search
query = "Graham Zemel"
for url in search(query):
print(url)Requires ‘google’ Python library to be installed before running.
(pip3 install google on command line)
Automated Browser Bot
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
bot = webdriver.Chrome(“chromedriver.exe”)
bot.get('https://grahamzemel.com')
search = bot.find_element(By.XPATH, '/html/body/div[2]/div[6]/div/div/main/div/div[3]')
# useful method:
# search.send_keys("Hello World")
search.click()
time.sleep(5)
# bot.quit()Requires ‘selenium’ Python library to be installed before running.
(pip3 install selenium on command line)
Create Custom Modules
# Find current path of Python script
import sys
print(sys.path)# my_module example: '/Users/grahamzemel/my_module' (no need to include '.py')
import my_module
my_module.my_function()Create Fake Data
import pandas as pd
from faker import Faker
# Create object
fake = Faker()
# Generate data
fake.name()
fake.text()
fake.address()
fake.email()
fake.date()
fake.country()
fake.phone_number()
fake.random_number(digits=5)
# Dataframe creation
fakeDataframe = pd.DataFrame({'date':[fake.date() for i in range(5)],
'name':[fake.name() for i in range(5)],
'email':[fake.email() for i in range(5)],
'text':[fake.text() for i in range(5)]})
print(fakeDataframe)Follow steps listed on above tools for dependency (/libraries — ‘pandas’ & ‘faker’) installation.
Nicely Formatted Strings
number = 1234.56
percentage = 0.33
big_number = 149839020429482
print(f'No formatting: {number}' # self explanatory
f'\nVariable name: {number = }' # self explanatory
f'\nConverted to two decimal place: {number:.2f}' # You can choose any number
f'\nChanging wide characters to 30: {number:30}' # The field will be 30 characters wide
f'\nAlign response to center: {number:^30}' # Left-aligned = less than 30 | right-aligned = greater than 30
f'\nFill white spaces: {number:=^30}' # Fill white spaces with any character
f'\nPrinting percent: {percentage_number:.2%}' # Multiply by 100 and add % symbol
f'\nTwo decimal places w/ comma: {high_number:,.2f}'
f'\nTwo decimal places w/ scientific notation: {high_number:.2e}'
)TQDM Progress Bar (A bit more advanced)
import pandas as pd
import numpy as np
from tqdm import tqdm
# Generate a dataframe with random numbers of shape 1,000 x 1,000
df = pd.DataFrame(np.random.randint(0, 100, (100000, 1000)))
# Register `pandas.progress_apply` with `tqdm`
tqdm.pandas(desc='Processing Dataframe')
# Add 3 to each value then cube for entire dataframe
df.progress_apply(lambda x: (x+3)**3)Result →
Processing Dataframe: 100%|██████████| 1000/1000 [00:02<00:00, 336.21it/s]Nato Alphabet Converter
import sys
nato_alphabet = {
'a': 'alpha',
'b': 'bravo',
'c': 'charlie',
'd': 'delta',
'e': 'echo',
'f': 'foxtrot',
'g': 'golf',
'h': 'hotel',
'i': 'india',
'j': 'juliet',
'k': 'kilo',
'l': 'lima',
'm': 'mike',
'n': 'november',
'o': 'oscar',
'p': 'papa',
'q': 'quebec',
'r': 'romeo',
's': 'sierra',
't': 'tango',
'u': 'uniform',
'v': 'victor',
'w': 'whiskey',
'x': 'x-ray',
'y': 'yankee',
'z': 'zulu'
}
try:
sys.argv[1]
except:
print("Usage: natoalphabet.py <word>")
exit(1)
for letter in sys.argv[1]:
if letter.lower() not in nato_alphabet:
print(letter)
else:
print(nato_alphabet[letter])Run using →
python3 natoalphabet.py Graham
Image Manipulation
from PIL import Image, ImageFilter
try:
original = Image.open("imagename.png")
# Blur the image
blurred = original.filter(ImageFilter.BLUR)
# Display both images
original.show()
blurred.show()
blurred.save("blurred.png")
except:
print "Unable to load image"Website Status
import requests
r = requests.get('https://blog.grahamzemel.com')
print(r.status_code)Thanks for reading about neat task flows in Python! If you enjoyed this post or learned something new, feel free to give it a few claps and check out The Gray Area for similar posts.
Support me and help me create even more content by subscribing to a Medium membership using my referral link →
Thanks!






