Creating a Python script that performs 15 different, interesting tasks can be a great way to explore the versatility of Python. Here's an example script that covers a variety of functionalities, including text processing, math operations, web scraping, and more:
import random
import string
import math
import requests
from bs4 import BeautifulSoup
import json
from datetime import datetime
import statistics
def generate_random_password(length=12):
return ''.join(random.choices(string.ascii_letters + string.digits + string.punctuation, k=length))
def factorial(n):
return math.factorial(n)
def fetch_website_title(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.title.string
def save_to_json(data, filename='data.json'):
with open(filename, 'w') as f:
json.dump(data, f)
def read_from_json(filename='data.json'):
with open(filename, 'r') as f:
return json.load(f)
def current_datetime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def primes_up_to(n):
primes = []
for possible_prime in range(2, n + 1):
is_prime = True
for num in range(2, int(math.sqrt(possible_prime)) + 1):
if possible_prime % num == 0:
is_prime = False
break
if is_prime:
primes.append(possible_prime)
return primes
def fibonacci(n):
sequence = [0, 1]
while len(sequence) < n:
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
def reverse_string(s):
return s[::-1]
def average(numbers):
return sum(numbers) / len(numbers)
def median(numbers):
return statistics.median(numbers)
def count_words(text):
words = text.split()
return len(words), len(set(words))
def is_palindrome(s):
return s == s[::-1]
def convert_to_uppercase(text):
return text.upper()
def square_numbers(numbers):
return [x**2 for x in numbers]
# Example usages of the functions:
print("Random Password:", generate_random_password())
print("Factorial of 5:", factorial(5))
print("Website Title:", fetch_website_title("https://www.example.com"))
data = {'name': 'Alice', 'age': 30}
save_to_json(data)
print("Read from JSON:", read_from_json())
print("Current DateTime:", current_datetime())
print("Primes up to 20:", primes_up_to(20))
print("First 10 Fibonacci numbers:", fibonacci(10))
print("Reverse of 'hello':", reverse_string("hello"))
numbers = [1, 2, 3, 4, 5]
print("Average:", average(numbers))
print("Median:", median(numbers))
text = "hello world hello"
print("Word Count:", count_words(text))
print("Is 'radar' a palindrome?", is_palindrome("radar"))
print("Uppercase 'hello world':", convert_to_uppercase("hello world"))
print("Square numbers:", square_numbers(numbers))
This script demonstrates how a single Python script can incorporate a mix of different functionalities. You can run it and modify it to suit your needs. Make sure you have the necessary libraries installed (e.g., requests, beautifulsoup4) for it to function correctly.