Five Cool Python Scripts that you need every day
Get ready to streamline your daily routine with a remarkable Python script that takes the hassle out of organizing your digital life. With its intuitive interface and intelligent algorithms, this script effortlessly categorizes and sorts your files, eliminating the frustration of searching through cluttered folders. Whether it's organizing your music library, tidying up your photo albums, or arranging your documents, this ingenious script saves you precious time and energy. Say goodbye to the chaos and experience a new level of efficiency as this Python script transforms your file management into a breeze.
Python Cool Program |
Image Conversion and Resizing Tool
The code prompts the user to enter the input path (file or folder), the desired output format, grayscale option, and width and height values. If the input is a file, it directly converts the image to the specified format. If the input is a folder, it iterates over all files in the folder and converts each image file to the desired format.
Code
from PIL import Image
import os
# Function to convert image format
def convert_image_format(image_path, output_format, grayscale, width, height):
image = Image.open(image_path)
if grayscale:
image = image.convert('L')
if width and height:
image = image.resize((width, height))
output_path = os.path.splitext(image_path)[0] + '.' + output_format
image.save(output_path)
print(f"Image converted and saved as {output_path}")
# Ask for input file or folder
input_path = input("Enter the path to the image file or folder: ")
# Ask for output image format
output_format = input("Enter the desired output image format (e.g., jpg, png, gif): ")
# Ask for grayscale option
grayscale_option = input("Do you want to convert the image to grayscale? (y/n): ")
grayscale = grayscale_option.lower() == 'y'
# Ask for width and height
width = int(input("Enter the desired width (in pixels), or 0 to maintain aspect ratio: "))
height = int(input("Enter the desired height (in pixels), or 0 to maintain aspect ratio: "))
# Check if the input is a file or a folder
if os.path.isfile(input_path):
convert_image_format(input_path, output_format, grayscale, width, height)
elif os.path.isdir(input_path):
# Iterate over all files in the folder
for file_name in os.listdir(input_path):
file_path = os.path.join(input_path, file_name)
if os.path.isfile(file_path):
convert_image_format(file_path, output_format, grayscale, width, height)
else:
print("Invalid path.")
Small Shopkeeper Inventory Management
The following code is a Python script that utilizes the SQLite database and the tabulate library to create a simple shop management system. It provides functionality to add products, make sales, update product details, delete products, retrieve data, and exit the program. The script begins with importing the necessary modules and establishing a connection to the SQLite database. It then creates a table for products if it doesn't already exist. The script defines various functions for each operation, such as adding a product, displaying products, deleting a product, updating product details, making a sale, and retrieving data. The main program loop presents a menu of options for the user to choose from, and based on their input, the corresponding function is executed. Finally, the script closes the database connection.
Code
import sqlite3
from tabulate import tabulate
# Connect to the SQLite database
conn = sqlite3.connect('shop.db')
c = conn.cursor()
# Create the products table if it doesn't exist
c.execute('''
CREATE TABLE IF NOT EXISTS products (
qrcode INTEGER PRIMARY KEY,
product_name TEXT,
quantity INTEGER,
price REAL
)
''')
conn.commit()
# Function to add a new product
def add_product():
qrcode = int(input("Enter the QR Code number: "))
product_name = input("Enter the product name: ")
quantity = int(input("Enter the quantity: "))
price = float(input("Enter the price: "))
c.execute('INSERT INTO products VALUES (?, ?, ?, ?)', (qrcode, product_name, quantity, price))
conn.commit()
print("Product added successfully!")
# Function to display all products
def display_products():
c.execute('SELECT * FROM products')
products = c.fetchall()
headers = ["QR Code", "Product Name", "Quantity", "Price"]
table = tabulate(products, headers=headers, tablefmt="fancy_grid")
print(table)
# Function to delete a product
def delete_product():
qrcode = int(input("Enter the QR Code number of the product to delete: "))
c.execute('DELETE FROM products WHERE qrcode = ?', (qrcode,))
conn.commit()
print("Product deleted successfully!")
# Function to update product details
def update_product():
qrcode = int(input("Enter the QR Code number of the product to update: "))
c.execute('SELECT * FROM products WHERE qrcode = ?', (qrcode,))
product = c.fetchone()
if product is None:
print("Product not found!")
else:
print("Product Details:")
print("QR Code:", product[0])
print("Product Name:", product[1])
print("Quantity:", product[2])
print("Price:", product[3])
quantity = int(input("Enter the new quantity: "))
price = float(input("Enter the new price: "))
c.execute('UPDATE products SET quantity = ?, price = ? WHERE qrcode = ?', (quantity, price, qrcode))
conn.commit()
print("Product updated successfully!")
# Function to make a sale
def make_sale():
total_amount = 0.0
sale_items = []
while True:
qrcode = int(input("Enter the QR Code number of the purchased product (or '0' to finish): "))
if qrcode == 0:
break
c.execute('SELECT * FROM products WHERE qrcode = ?', (qrcode,))
product = c.fetchone()
if product is None:
print("Product not found!")
else:
quantity = int(input("Enter the quantity purchased: "))
if quantity <= product[2]:
sale_items.append((product[0], product[1], quantity, product[3]))
total_amount += product[3] * quantity
else:
print("Insufficient quantity!")
print("Sale Details:")
headers = ["QR Code", "Product Name", "Quantity", "Price"]
table = tabulate(sale_items, headers=headers, tablefmt="fancy_grid")
print(table)
amount_given = float(input("Enter the amount given by the customer: "))
change = amount_given - total_amount
if change < 0:
print("Insufficient amount!")
else:
print("Change to give:", change)
# Update the quantity of sold items
for item in sale_items:
c.execute('UPDATE products SET quantity = quantity - ? WHERE qrcode = ?', (item[2], item[0]))
conn.commit()
# Function to retrieve sales and inventory data in table format
def retrieve_data():
c.execute('SELECT qrcode, product_name, quantity, price FROM products')
data = c.fetchall()
headers = ["QR Code", "Product Name", "Quantity", "Price"]
table = tabulate(data, headers=headers, tablefmt="fancy_grid")
print(table)
c.execute('SELECT SUM(quantity * price) FROM products')
total_sales = c.fetchone()[0]
c.execute('SELECT SUM(quantity) FROM products')
total_quantity = c.fetchone()[0]
print("Total Sales:", total_sales)
print("Total Quantity Remaining:", total_quantity)
# Main program loop
while True:
print("1. Add Product")
print("2. Make Sale")
print("3. Retrieve Data")
print("4. Update Product")
print("5. Delete Product")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
add_product()
elif choice == 2:
make_sale()
elif choice == 3:
retrieve_data()
elif choice == 4:
update_product()
elif choice == 5:
delete_product()
elif choice == 6:
break
else:
print("Invalid choice!")
# Close the database connection
conn.close()
Frames Skipping in Video
Python code that uses OpenCV library to skip a specified number of frames in a video and rewrite the output to a new file, The code prompts the user to enter the input video file path, output video file path, and the number of frames to skip. After processing the video, it prints the number of frames skipped and the path of the output file.
Make sure you have the OpenCV library installed (pip install opencv-python) before running this code. Also, note that the output video file format is set to MP4 (mp4v) in the code. You can change it if needed based on your requirements.
Code
import cv2
def skip_frames_and_rewrite(input_file, output_file, frames_to_skip):
cap = cv2.VideoCapture(input_file)
fps = cap.get(cv2.CAP_PROP_FPS)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Calculate the number of frames to keep
frames_to_keep = total_frames // frames_to_skip
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_file, fourcc, fps, (int(cap.get(3)), int(cap.get(4))))
frame_count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Write the frame to the output file
if frame_count % frames_to_skip == 0:
out.write(frame)
frame_count += 1
# Release the resources
cap.release()
out.release()
print(f"Frames skipped: {frames_to_skip}")
print(f"Output file saved as: {output_file}")
# Prompt user for input
input_file = input("Enter the input video file path: ")
output_file = input("Enter the output video file path: ")
frames_to_skip = int(input("Enter the number of frames to skip: "))
# Call the function
skip_frames_and_rewrite(input_file, output_file, frames_to_skip)
An Advanced Health Calculator
def calculate_bmi(weight, height):
"""Calculate Body Mass Index (BMI)"""
bmi = weight / (height ** 2)
return bmi
def calculate_bmr(weight, height, age, gender):
"""Calculate Basal Metabolic Rate (BMR)"""
if gender.lower() == "male":
bmr = 10 * weight + 6.25 * height * 100 - 5 * age + 5
elif gender.lower() == "female":
bmr = 10 * weight + 6.25 * height * 100 - 5 * age - 161
else:
return None
return bmr
def calculate_tdee(bmr, activity_level):
"""Calculate Total Daily Energy Expenditure (TDEE)"""
activity_factors = {
"sedentary": 1.2,
"lightly active": 1.375,
"moderately active": 1.55,
"very active": 1.725,
"extra active": 1.9
}
tdee = bmr * activity_factors.get(activity_level.lower(), 1.2)
return tdee
def calculate_ideal_weight(height, gender):
"""Calculate Ideal Body Weight"""
if gender.lower() == "male":
ideal_weight = 50 + 0.91 * (height - 152.4)
elif gender.lower() == "female":
ideal_weight = 45.5 + 0.91 * (height - 152.4)
else:
return None
return ideal_weight
def calculate_health_metrics():
weight = float(input("Enter your weight (in kg): "))
height = float(input("Enter your height (in meters): "))
age = int(input("Enter your age: "))
gender = input("Enter your gender (male/female): ")
activity_level = input("Enter your activity level "
"(sedentary/lightly active/moderately active/very active/extra active): ")
bmi = calculate_bmi(weight, height)
bmr = calculate_bmr(weight, height, age, gender)
tdee = calculate_tdee(bmr, activity_level)
ideal_weight = calculate_ideal_weight(height, gender)
print("\n--- Health Metrics ---")
print(f"BMI: {bmi:.2f}")
print(f"BMR: {bmr:.2f} calories/day")
print(f"TDEE: {tdee:.2f} calories/day")
if ideal_weight:
print(f"Ideal Body Weight: {ideal_weight:.2f} kg")
# Call the function to calculate health metrics
calculate_health_metrics()
In this script, we have the following health metrics calculations:
Body Mass Index (BMI): Calculated using the weight and height inputs.
Basal Metabolic Rate (BMR): Calculated based on weight, height, age, and gender inputs. The Harris-Benedict equation is used.
Total Daily Energy Expenditure (TDEE): Calculated using BMR and activity level inputs. An activity factor is applied to BMR to estimate the daily caloric needs.
Ideal Body Weight: Calculated based on height and gender inputs. The Devine formula is used.
Basic Stock Analysis
In this script, we utilize the yfinance library to download stock data from Yahoo Finance. We then calculate and plot the stock prices as well as the daily returns. The script also computes several key statistics such as average daily return, standard deviation of daily return, annualized return, and annualized volatility. Finally, it displays the statistics to the user.
To run this script, you will need to have the yfinance and matplotlib libraries installed (pip install yfinance matplotlib). Please note that
stock market data is subject to availability and may not be available for all ticker symbols or time periods.
Feel free to customize or expand the script based on your specific stock analysis requirements or add additional analysis techniques such as moving averages, technical indicators, or regression models.
Code
import yfinance as yf
import matplotlib.pyplot as plt
def analyze_stock(ticker):
# Download stock data from Yahoo Finance
stock_data = yf.download(ticker, start='2022-01-01', end='2022-12-31')
# Calculate daily returns
stock_data['Daily_Return'] = stock_data['Adj Close'].pct_change()
# Plotting the stock prices
plt.figure(figsize=(10, 6))
plt.plot(stock_data['Adj Close'])
plt.title(f'{ticker} Stock Prices')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.grid(True)
plt.show()
# Plotting the daily returns
plt.figure(figsize=(10, 6))
plt.plot(stock_data['Daily_Return'])
plt.title(f'{ticker} Daily Returns')
plt.xlabel('Date')
plt.ylabel('Return')
plt.grid(True)
plt.show()
# Calculate statistics
mean_return = stock_data['Daily_Return'].mean()
std_return = stock_data['Daily_Return'].std()
annualized_return = mean_return * 252 # Assuming 252 trading days in a year
annualized_volatility = std_return * (252 ** 0.5) # Assuming 252 trading days in a year
# Print the statistics
print('--- Stock Analysis ---')
print(f'Ticker: {ticker}')
print(f'Average Daily Return: {mean_return:.4f}')
print(f'Standard Deviation of Daily Return: {std_return:.4f}')
print(f'Annualized Return: {annualized_return:.4f}')
print(f'Annualized Volatility: {annualized_volatility:.4f}')
# Prompt the user to enter the stock ticker symbol
ticker = input('Enter the stock ticker symbol: ')
# Call the function to analyze the stock
analyze_stock(ticker)
No comments:
Post a Comment