PromptBase
Close icon
Explore
Marketing & BusinessDown chevron icon
General
Home
Marketplace
Apps
Create
Hire
Login
Sell
Outlined heart icon
🤖 GPT

Optimized Python Solution

Optimized Python Solution gpt prompt mini thumbnail
57Eye icon
Views
TestedTick icon
TipsTick icon
Unlock the power of Python with this meticulously crafted prompt, designed by a seasoned expert with 44 years of experience. Elevate your coding prowess as you tackle [Specific Task] using efficient and scalable solutions. Embrace industry best practices and unleash the potential of [module/library], all within a neatly commented and comprehensible code structure. Elevate your coding game with this expert-curated prompt, making Python coding a breeze.
...more
$4.99
Get prompt
Add to cart icon
After purchasing, you will gain access to the prompt file which you can use with GPT or the app builder. You'll receive 20 free generation credits with this purchase. By purchasing this prompt, you agree to our terms of service.
Updated: 4 months ago

Prompt Details

Model
Chat - GPT-3.5 (gpt-3.5-turbo)
Token size
100 ($0.00010 / call)
Example input
[specific task or objective] [module/library]
Example output
**Objective:** Create a well-structured and concise Python code that fetches weather information for a given city using an API. **Utilize Module/Library:** `requests` for making HTTP requests and `json` for handling JSON responses. **Optimization:** The code is optimized for efficiency by handling potential errors gracefully and using appropriate HTTP status codes for validation. **Coding Standards/Good Practices:** Follow PEP 8 coding standards and include meaningful variable/function names and comments for clarity. **Test Cases/Scenarios:** Test the code with a valid city, an invalid city, and handle potential edge cases like a network failure or an unreachable API. ```python import requests import json def get_weather(city_name): """ Fetches weather information for a given city using an API. Args: - city_name (str): Name of the city. Returns: - dict: Weather information in a dictionary format. Raises: - requests.exceptions.RequestException: If there is an issue with the HTTP request. - ValueError: If the city name is not provided or the API response is not in JSON format. """ # Check if the city name is provided if not city_name: raise ValueError("City name is required.") # API endpoint for weather information api_url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid=YOUR_API_KEY" try: # Make the HTTP request response = requests.get(api_url) # Check if the request was successful (HTTP status code 200) response.raise_for_status() # Parse the JSON response weather_data = response.json() # Check if the response contains weather information if "main" in weather_data and "weather" in weather_data: return weather_data else: raise ValueError("Invalid response format. Missing weather information.") except requests.exceptions.RequestException as req_err: raise req_err except json.JSONDecodeError: raise ValueError("Invalid JSON format in the API response.") if __name__ == "__main__": # Test cases try: # Valid city city_weather = get_weather("London") print("Weather in London:", city_weather) # Invalid city invalid_city_weather = get_weather("InvalidCityName") print("Weather in InvalidCityName:", invalid_city_weather) except requests.exceptions.RequestException as req_err: print(f"Error making HTTP request: {req_err}") except ValueError as value_err: print(f"ValueError: {value_err}") ``` **Comments:** - Replace `"YOUR_API_KEY"` in the `api_url` variable with a valid OpenWeatherMap API key. - The `get_weather` function returns a dictionary containing weather information or raises appropriate exceptions. - Test cases demonstrate how to use the `get_weather` function for both valid and invalid city names. - Handle exceptions to provide meaningful error messages. - Ensure to keep sensitive information (like API keys) secure and do not share them in public repositories.
Browse Marketplace