5 Cool Things You Can Do with Python

Hello friend, you‘ve likely heard about Python being used across websites like YouTube, Instagram and Reddit. But did you know it can also help build complex AI systems, hack vulnerabilities and create games? Let‘s explore some of the possibilities!

Python started off in the late 1980s and has seen immense growth over the years. The global Python developer community stands at over 8 million according to the 2020 JetBrains survey.

Major tech giants like Google, Facebook, Amazon and Netflix use Python extensively for production systems and data pipelines. This massive adoption is driven by Python‘s simplicity, vast libraries and vibrant ecosystem.

In this post, I have covered some of the popular use cases and domains where Python shines:

  • Web Scraping & Automation
  • Machine Learning & Data Science
  • Game Development
  • Web Applications
  • Cybersecurity & Hacking

I have explained each with simple code examples and topics you can explore further. Let‘s get started!

Web Scraping & Automation

While most websites explicitly disallow scraping, Python makes it extremely simple to extract and parse information from the web. We can even automate repetitive tasks like system administration, file processing and monitoring.

Here is some sample code to scrape Amazon for product details:

import requests 
from bs4 import BeautifulSoup

URL = ‘https://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994‘

page = requests.get(URL)

soup = BeautifulSoup(page.content, ‘html.parser‘)
title = soup.find(id=‘productTitle‘).get_text().strip() 

print(title)
# Output: Automate the Boring Stuff with Python: Practical Programming for Total Beginners

While the above works, large sites like Amazon have defenses against scraping bots. So we need robust tools like Selenium to emulate user browsers for dynamic content:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get(‘https://www.amazon.com‘)  

search_box = driver.find_element(By.ID, ‘twotabsearchtextbox‘)
search_box.send_keys(‘python books‘)

search_box.submit()  

results = driver.find_elements(By.XPATH, ‘//div[@data-component-type="s-search-result"]‘)

for item in results:
    print(item.text)

driver.close()

This automation script searches for "python books" and prints results. Scrapy is a popular alternative to handle complex scraping needs at scale.

Machine Learning & Data Science

Python plays a pivotal role in data science thanks to libraries like Pandas, NumPy and SciKit Learn. Researchers and engineers alike use Jupyter notebooks for everything from data cleaning to model building.

While coding ML algorithms from scratch help understand them better, most real world scenarios rely on battle-tested libraries. Let‘s see sample code to train an image classifier with Keras:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

data = keras.datasets.fashion_mnist  

(train_images, train_labels), (test_images, test_labels) = data.load_data()

# Building the model  
model = keras.Sequential([
    layers.Dense(512, activation=‘relu‘),  
    layers.Dense(10, activation=‘softmax‘)])  

# Compile model
model.compile(optimizer=‘adam‘,
              loss=‘sparse_categorical_crossentropy‘,
              metrics=[‘accuracy‘])

# Train Model 
model.fit(train_images, train_labels, epochs=5)  

# Evaluate accuracy  
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(‘Test accuracy:‘, test_acc)

The above 93% accurate image classifier relies on just 20 lines of actual model code!

Python‘s near limitless libraries enable building models for cases like time series forecasting, natural language processing and more. Frameworks like TensorFlow and infrastructure improvements with GPU/TPU make Python a solid choice for machine learning engineers.

Game Development

For creative coders and game developers, Python powered frameworks like Pygame and Pyglet provide crossover from basic scripts to high powered games.

Pygame‘s architecture centers around an event loop and comes integrated with the SDL2 library for rich cross-platform media capabilities. Let‘s see a simple Pygame example:

import pygame

pygame.init()  
screen = pygame.display.set_mode((640, 480)) 

running = True
while running:
    for event in pygame.event.get():   
        if event.type == pygame.QUIT:
            running = False

    screen.fill((250, 120, 60))
    pygame.display.flip()  

pygame.quit()

This small script opens up a 640×480 pixel window and fills the background with orange red. We can detect OS events like quit or keypresses inside the loop.

With these building blocks, full fledged games like platformers and top down RPGs can be crafted with Pygame‘s sprite, sound and graphics features.

Web Applications

For beginner web developers and hobbyists, Python frameworks like Django and Flask provide simple APIs to CRUD applications. These remove a ton of boilerplate around servers, routing and databases.

Consider this basic web app with Flask:

from flask import Flask, render_template  

app = Flask(__name__)

@app.route(‘/‘)
def home():
    return render_template(‘home.html‘)

if __name__ == ‘__main__‘:  
    app.run(debug=True)

The built-in templating and routing enables building pages dynamically. While Flask provides more control, Django has batteries included with its MTV architecture:

# views.py
from django.shortcuts import render

def home(request):
    context = {
        ‘title‘:‘My Django App‘,
        ‘subtitle‘:‘Made with Python‘ 
    }
    return render(request, ‘home.html‘, context)

Django handles interacting with data, authentication systems and content delivery out of the box. This helps rapid prototyping of ideas before worrying about complex infrastructure needs.

Cybersecurity & Hacking

Python is widely used as a scripting language by penetration testers for its versatility and stealth. It also provides bindings to many C/C++ security tools and flexibility of quick scripts ideal for red teams.

Consider automating reconnaissance with a simple port scanner:

import socket
import threading
from queue import Queue

target = "10.0.0.138"
queue = Queue()  
open_ports = []

def portscan(port):  
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((target, port))
        open_ports.append(port)  
    finally:
        sock.close()

def threader():
    while True:
        worker = queue.get()  
        portscan(worker)  
        queue.task_done()   

for x in range(100):
     t = threading.Thread(target=threader)  
     t.daemon = True  
     t.start()  

for worker in range(1, 1024):  
    queue.put(worker)

queue.join()
print(‘Open Ports are:‘, open_ports)

This demonstrates a basic threaded port scanner for checking vulnerabilities. Python enables building far more complex exploits, trojans and reverse shells needed for offensive security.

Of course, caution should be exercised to avoid breaking laws. But understanding both sides of security helps defend systems better. Libraries focussed on infosec tasks make Python an ally for white, grey and black hat hackers alike!

Conclusion

Throughout this article, we explored some of the possibilities Python offers across domains with simple code examples. Python‘s versatility, readability and sheer power of libraries spark endless ideas for developers and hackers like yourself!

I hope by now you have gotten a glimpse into building games, machine learning models and web applications using Python. The community keeps crafting incredible tools like PyTorch, Django and Tensorflow expanding Python‘s capabilities.

If any of these domains excited you, I suggest digging deeper into dedicated tutorials and guides. Do you have any other favorite Python use cases? Let me know in the comments below!