Introduction
One of my favorite languages is Python. No excuses I use it a lot lately despite it being slow. Why? Well this is what I’m going to break down in this article. Take this from a C enthusiast and lover of lightweight and fast languages. Python has won a place in my heart and for a good reason.
Python’s popularity can be attributed to its simplicity, readability, and versatility. It has a plethora of libraries that help developers build applications quickly without the need to reinvent the wheel. Python’s dynamic nature allows developers to write code at a faster pace compared to other languages, making the development process more productive.
As for its speed, Python may not be the fastest language compared to compiled languages like C or C++. Still, it has an extensive ecosystem of libraries that provide fast implementations of computationally intensive tasks. Additionally, Python can easily leverage multithreading, multiprocessing, and distributed computing frameworks to improve performance, making it relatively faster in those scenarios.
Here are ten examples of long-form detailed Python code snippets that showcase the language’s versatility.
Building a Web Application with Flask
Flask is a lightweight Python web framework that makes it easy for developers to create web applications. The following code creates a simple Flask application that returns ‘Hello world!’ when accessed through a browser:
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello world!' if __name__ == '__main__': app.run()
The code imports the Flask library, creates an instance of the Flask application, maps a URL endpoint to a function that returns a static string, and runs the application if it is called as the main module.
Creating a Machine Learning Model using scikit-learn
Scikit-learn is a popular Python library used for machine learning. The following code trains a decision tree classifier on the Iris dataset to predict flower species:
from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split iris = load_iris() X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42) clf = DecisionTreeClassifier(random_state=42) clf.fit(X_train, y_train) score = clf.score(X_test, y_test) print('Accuracy:', score)
The code first imports necessary libraries, loads the Iris dataset, splits it into training and test sets, defines a decision tree classifier, fits the model to the training data, evaluates the accuracy of the model on the test set, and prints the result.
Building a GUI using PyQt5
PyQt5 is a Python binding for the popular Qt application framework. The following code creates a simple graphical user interface (GUI) window with a button using PyQt5:
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): btn = QPushButton('Button', self) btn.setToolTip('This is a button') btn.move(50, 50) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Example') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
The code imports necessary libraries, creates a class that inherits from QWidget, adds a button with a tooltip to the widget, defines the window size and title, and displays the window if called as the main module.
Parsing an XML file with ElementTree
ElementTree is a built-in Python library used for parsing and manipulating XML files. The following code parses an example XML file and extracts information from its tags:
import xml.etree.ElementTree as ET tree = ET.parse('example.xml') root = tree.getroot() for child in root: print(child.tag, child.text)
The code first imports the ElementTree library, opens an XML file, reads its root element, and iterates through all of its children to retrieve their tag names and text values.
Creating a TCP Client/Server Application
Python’s built-in socket library allows developers to create TCP/IP client/server applications quickly. The following code creates a simple echo server that sends back any text sent to it by a client:
Server:
import socket HOST = 'localhost' PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) while True: data = conn.recv(1024) if not data: break conn.sendall(data)
The code defines a server socket, binds it to the specified address and port, listens for incoming connections, accepts a new connection, and sends back any received data.
Client:
import socket HOST = 'localhost' PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(b'Hello, world') data = s.recv(1024) print('Received', repr(data))
The code defines a client socket, connects to the server at the specified address and port, sends a message, waits for a response, and displays it.
Scraping a Web Page with BeautifulSoup
BeautifulSoup is a popular Python library used for web scraping. The following code scrapes the title and URLs of articles on the front page of Reddit:
import requests from bs4 import BeautifulSoup URL = 'https://www.reddit.com/' response = requests.get(URL) soup = BeautifulSoup(response.content, 'html.parser') for post in soup.find_all('div', class_='Post'): title = post.find('h3', class_='Post__title').text.strip() url = post.find('a', class_='Post__title__link')['href'] print(title) print(url)
The code imports necessary libraries, sends a GET request to a website, parses its HTML content with BeautifulSoup, iterates through each article’s div element on the page, extracts the title and URL of each post, and prints them.
Integrating With an API using Requests
Python’s requests library provides a simple interface for making HTTP requests to APIs. The following code retrieves current weather data from OpenWeatherMap’s API and displays it:
import requests API_KEY = 'your_api_key' CITY = 'New York' url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}' response = requests.get(url) data = response.json() description = data['weather'][0]['description'].capitalize() temperature = round(data['main']['temp'] - 273.15, 1) print(f'Today in {CITY}: {description}, temperature is {temperature}°C')
The code defines an API URL including parameters such as the location and API key, sends a GET request to retrieve the data, extracts relevant information from the JSON response, and prints it.
Using Regular Expressions to Match Patterns
Python has built-in support for regular expressions, which allow developers to match patterns in text. The following code searches for all matches of a specific pattern in a sample string:
import re text = 'This is a sample string. The quick brown fox jumps over the lazy dog.' pattern = r'\b\w{5}\b' matches = re.findall(pattern, text) print(matches)
The code imports the regular expression library, defines a pattern to match words with exactly five characters, uses the findall() method to find all matches in the text and returns them.
Creating a Multi-threaded Application
Python threads allow developers to write concurrent applications that perform multiple tasks simultaneously. The following code creates three threads that each count from 1 to 10:
import threading def count(start, end): for i in range(start, end+1): print(f'{threading.current_thread().name}: {i}') t1 = threading.Thread(target=count, args=(1, 10)) t2 = threading.Thread(target=count, args=(11, 20)) t3 = threading.Thread(target=count, args=(21, 30)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join()
The code defines a function that counts from a start to an end number, creates three threads with different start and end values, starts each thread to execute the function concurrently, waits for each thread to finish executing, and prints the results.
Implementing a Binary Tree in Python
Python provides various data structures like lists, dictionaries, sets, etc. Still, it also allows developers to implement more complex ones such as binary trees. The following code implements the Binary Tree data structure using Python’s classes and recursion:
class BinaryTree: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def insert_left(self, value): if self.left_child is None: self.left_child = BinaryTree(value) else: new_node = BinaryTree(value) new_node.left_child = self.left_child self.left_child = new_node def insert_right(self, value): if self.right_child is None: self.right_child = BinaryTree(value) else: new_node = BinaryTree(value) new_node.right_child = self.right_child self.right_child = new_node def traverse_inorder(self): if self.left_child: self.left_child.traverse_inorder() print(self.value) if self.right_child: self.right_child.traverse_inorder() root = BinaryTree(1) root.insert_left(2) root.insert_right(3) root.left_child.insert_left(4) root.left_child.insert_right(5) root.right_child.insert_left(6) root.right_child.insert_right(7) root.traverse_inorder()
The code defines a BinaryTree class with methods to insert nodes on the left or right of a given node, as well as traverse the tree in order recursively. The main code creates an instance of the binary tree, inserts nodes with values 2-7 at various positions, and prints the values in order as they are traversed.
Conclusion
Hopefully by now you can see my excuse of why I still use Python. Rightfully me and a lot of other people share the same thoughts on it and I believe Python holds a the throne of simplicity and a plethora of libraries that I discussed above which make it unique and good for beginners. The idea of being able to touch so many people even at early stages of their coding journey increases it’s popularity. If we quickly check google trends Python is always on the rise and the reason for this is that a lot of new projects choose it for it’s simplicity. If you combine new projects and the ease of use that makes the cost to enter development easy it makes a lot of sense that Python is very popular despite being slow.