Python

A shared tag with AI prompts and code snippets

From workspace: Replit

Team: AI Prompts

Total snippets: 29

Replit

Python

29 snippets

7. Use AI to Summarize Spending Behavior

Send expenses to OpenAI to get financial behavior feedback.

Create a new Flask endpoint `/summary`: – Reads `expenses.json` – Sends data to OpenAI Chat API with prompt: "Analyze this week's expenses. Highlight overspending, trends, and improvement tips." Return short paragraph summary.

5. Store Expenses in Local JSON Format

Persist expenses on backend using a simple JSON file.

Update Flask logic to save submitted expenses to `expenses.json`. – On each POST: append to file – Add GET `/expenses` to return all Ensure file is created if not found.

3. Create Flask Endpoint for Saving Expenses

Build a backend endpoint that receives and stores submitted expenses.

Create a Flask endpoint `/expense` that: – Accepts POST requests – Accepts JSON with amount, category, description – Stores in a local list or temporary variable – Returns confirmation response Enable CORS for localhost:3000.

6. Generate Positive Affirmations

Use AI to generate daily affirmations based on journal themes.

Add OpenAI logic to return 2–3 affirmations based on journal tone/themes. Prompt format: "Generate 3 personalized affirmations for someone who feels {mood} about {themes}." Return as array of strings in JSON.

5. Analyze Sentiment and Tone with OpenAI

Use OpenAI API to analyze mood, tone, and themes of journal entry.

Extend the Flask endpoint to: – Use OpenAI's Chat API – Prompt: “Analyze this journal entry. Return mood, tone, and emotional themes.” – Return JSON like: { "mood": "Anxious but hopeful", "themes": ["uncertainty", "self-reflection", "growth"] }

3. Create Flask Endpoint to Receive Journal Entry

Build a Flask API to receive and store journal text for AI processing.

Create a Flask endpoint `/entry` that: – Accepts POST requests – Receives `entry_text` from JSON body – Logs it or saves to a temporary variable for now – Returns success JSON response Enable CORS for localhost:3000.

6. Send Resume Text to AI for Feedback

Send extracted resume text to OpenAI API and return summary.

Add AI analysis logic to Flask: – Use OpenAI's Chat API – Prompt: "Analyze this resume and give strengths, weaknesses, and job fit" – Use extracted text as input – Return feedback to frontend Keep API key secure in .env.

5. Add Resume Text Extraction in Flask

Extract text from uploaded .pdf or .txt file in Flask.

Extend the `/upload` Flask endpoint to: – If file is .txt → read with open() – If file is .pdf → extract text using `PyMuPDF` or `pdfminer.six` – Return extracted text in JSON: `{ text: "..." }`

Use Python to Get Weather via API

Query weather data using requests and print the current temp.

import requests res = requests.get('https://api.weatherapi.com/v1/current.json', params={ 'key': 'your_api_key', 'q': 'Lisbon' }) data = res.json() print("Temp (°C):", data['current']['temp_c'])

Submit Form Data to API in Python

Send a POST request with a JSON payload using the requests library.

import requests payload = {'email': 'test@example.com', 'password': '1234'} res = requests.post('https://api.example.com/login', json=payload) print(res.status_code, res.json())

Identify SQL Injection Risk

Detect and fix potential SQL injection in backend code.

Review this Python code for SQL injection risks. Suggest secure fixes using parameterized queries. Code: def get_user(email): query = f"SELECT * FROM users WHERE email = '{email}'" return db.execute(query)

Python Script to Rename Files in Bulk

Write a Python script to batch rename files with a prefix.

Write a script to: – Rename all `.txt` files in a folder – Add prefix 'renamed_' to each filename – Show before/after filenames Use pathlib or os.

Python CLI with Argparse

Generate a Python CLI tool that accepts arguments using argparse.

Write a Python CLI that: – Accepts two numbers – Has a flag for addition or subtraction – Prints the result Use argparse for argument parsing.

Use BeautifulSoup to Scrape Links

Extract all hyperlinks from HTML using BeautifulSoup.

Use BeautifulSoup to extract all `<a href="">` links. HTML: <html> <body> <a href="https://example.com">Example</a> <a href="https://test.com">Test</a> </body> </html>

Use SQLAlchemy to Define Models

Define a User and Post model using SQLAlchemy ORM.

Define SQLAlchemy models with relationships. Models: – User: id, name, email – Post: id, title, user_id (FK) Include: – Base class – One-to-many relationship – `__repr__` methods

Use Matplotlib to Plot Bar Chart

Plot a labeled bar chart using Matplotlib.

Use Matplotlib to create a bar chart. Data: products = ['A', 'B', 'C'] sales = [120, 300, 90] Chart should: – Show labels – Add title 'Product Sales' – Color bars Also show the final rendered chart.

Use Pandas to Clean a CSV

Show how to clean and transform a CSV using Pandas.

Show how to clean this CSV using Pandas. Tasks: – Remove rows with missing 'email' – Convert 'signup_date' to datetime – Filter users with 'active' == True Data: users.csv | id | email | signup_date | active...

Explain Python List Comprehension

Explain how this list comprehension works and what it returns.

Explain what this list comprehension does. Code: nums = [1, 2, 3, 4, 5] squares = [x*x for x in nums if x % 2 == 0] Include: – How filtering works – Final result list

Explain Python Recursion Line by Line

Explain a recursive Python function line by line in plain English.

Explain this recursive function line by line. Goal: – Help beginners understand how recursion works – Include base and recursive case flow Code: def factorial(n): if n == 0: return 1 return n * factorial(n - 1)

Refactor Global State Into Class

Encapsulate global variables and functions into a class.

This code uses global state. Refactor by moving everything into a class. Code: settings = {'theme': 'dark'} def get_theme(): return settings['theme'] def set_theme(t): settings['theme'] = t

Convert For Loop to Map/Filter

Simplify a loop using functional programming methods.

Convert the loop to a functional style using `map` or `filter`. Code: names = ['Alice', 'Bob', 'Charlie'] upper = [] for name in names: if len(name) > 3: upper.append(name.upper())

Refactor Long Function to Smaller Functions

Split a long function into smaller, readable, reusable units.

Refactor this long function into smaller helper functions. Goals: – Improve readability – Make code easier to test – Avoid repetition Code: def process_user_data(user): if '@' not in user['email']: raise ValueError('Invalid email') ...

Add Edge Case Tests for Sorting Function

Add edge case tests for a sorting algorithm.

Add test cases for this sorting function. Cover: – Empty list – One item – Already sorted – Repeated values Code: def sort_numbers(arr): return sorted(arr)

Add Integration Test for Flask Route

Write an integration test for a Flask endpoint using Flask's test client.

Write an integration test for this Flask route using `app.test_client()`. Test: – Valid credentials – Wrong credentials – Status codes – JSON response Code: @app.route('/login', methods=['POST']) def login(): data = request.get_json() if...

Test Coverage Suggestions

Review a function and suggest missing test cases.

You are reviewing this function for test coverage. Identify: – Edge cases not covered – Unexpected or null input – Suggestions for improved testing Code: def format_price(value): if value is None: return "N/A" return...

Unit Tests for Python Function

Generate comprehensive unit tests for a given Python function using

You are given a Python function. Write unit tests using `pytest`. Cover: – Valid input – Invalid input – Edge cases (e.g. empty lists, negative numbers) – Exceptions and assertions Code: def divide_numbers(a, b): return a / b

Avoid KeyError in Flask Form

Fix a Flask bug where missing form data causes a crash.

This line throws a KeyError if the 'username' field is missing. Make it safe while preserving access to the form. Code: username = request.form['username']

Handle None Input in Python

Fix function that crashes when input is None

This function crashes when given `None` instead of a list. Add type checking and make it safe for invalid input. Code: def find_even(numbers): for i in range(len(numbers)): if numbers[i] % 2 == 0: return i return...

Fix TypeError in Python Function

Debug a TypeError caused by incompatible data types in a function.

Analyze the following Python function that raises a `TypeError` during execution. Add inline explanation and rewrite the fixed version. Example: – Understand cause of failure from traceback – Suggest type-safe handling Code: def add_items(a,...