Powerful Mini-Programs in 30 Lines of Python Code

Python, as a highly concise and expressive programming language, allows developers to create powerful programs in a surprisingly small number of lines. In this blog post, we’ll explore the potential of Python by creating mini-programs using just 30 lines of code.

1. Simple Web Server

With the help of the http.server module in Python’s standard library, you can set up a basic web server in just a few lines. Here’s an example:

pythonimport http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Serving at port", PORT)
httpd.serve_forever()

2. Fibonacci Sequence Generator

A Fibonacci sequence is a series of numbers where each number is the sum of the two preceding numbers. Here’s a short program that generates the first 10 Fibonacci numbers:

pythondef fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

for num in fibonacci(10):
print(num)

3. Password Generator

A simple password generator can be created using Python’s random module:

pythonimport random
import string

def generate_password(length=10):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for i in range(length))

print(generate_password(10))

4. Text File Reader

A program to read the contents of a text file can be written in just a few lines:

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

5. Temperature Converter

A simple program to convert Fahrenheit to Celsius:

pythondef fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9

fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit}°F is equal to {celsius}°C")

Each of these programs demonstrates the power and conciseness of Python. While they are simple, they highlight the potential of writing efficient and effective programs in a small number of lines.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *