Introduction #
Python is one of the most versatile programming languages, and its simplicity makes it great for solving everyday problems. In this post, we’ll go through nine practical Python examples that cover common applications across different domains—from text processing and file handling to web automation and data visualization.
1. Text Processing: Word Frequency Counter #
text = "This is a sample text for word frequency analysis."
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
Counts how many times each word appears in a given text.
2. File Operations: Copying Files #
import shutil
src_file = 'source.txt'
dest_file = 'destination.txt'
shutil.copyfile(src_file, dest_file)
Copies the contents of one file to another.
3. Network Requests: Sending a GET Request #
import requests
url = 'https://api.example.com/data'
response = requests.get(url)
print(response.text)
Fetches data from an API endpoint and prints the response.
4. Data Parsing: Working with JSON #
import json
json_data = '{"name": "John", "age": 25}'
data = json.loads(json_data)
print(data['name'])
Parses JSON data and accesses specific fields.
5. Database Operations: Querying SQLite #
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
Connects to an SQLite database and retrieves rows from a table.
6. Image Processing: Resize an Image #
from PIL import Image
image = Image.open('image.jpg')
resized_image = image.resize((800, 600))
resized_image.save('resized_image.jpg')
Uses Pillow (PIL) to resize and save an image.
7. Data Science: Matrix Operations with NumPy #
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2)
print(result)
Performs a matrix multiplication using NumPy.
8. Web Automation: Selenium Browser Control #
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.vxworks6.com')
element = driver.find_element("id", "element_id")
print(element.text)
driver.close()
Automates browser actions like visiting a website and reading page content.
9. Data Visualization: Plot a Line Graph #
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Line Graph')
plt.show()
Plots a simple line graph using Matplotlib.
Conclusion #
These nine Python examples demonstrate just how versatile the language can be. From handling text and files to working with databases, images, automation, and visualization—Python provides libraries and tools to make programming tasks straightforward and effective.
👉 Try customizing these snippets for your own projects, and you’ll quickly see why Python is a favorite among developers.