News Froggy
newsfroggy
HomeTechReviewProgrammingGamesHow ToAboutContacts
newsfroggy

Your daily source for the latest technology news, startup insights, and innovation trends.

More

  • About Us
  • Contact
  • Privacy Policy
  • Terms of Service

Categories

  • Tech
  • Review
  • Programming
  • Games
  • How To

© 2026 News Froggy. All rights reserved.

TwitterFacebook
Programming

Building a Python CLI Weather App: Fetching Data & Handling Input

This tutorial guides developers through building a command-line weather application using Python. It covers fetching current temperature and wind speed by interacting with external APIs, specifically for geocoding city names into coordinates and then retrieving weather data. Key learning points include making HTTP requests, parsing JSON, handling command-line arguments with `sys`, and implementing robust error handling.

PublishedOctober 29, 2026
Reading Time9 min
Building a Python CLI Weather App: Fetching Data & Handling Input

As developers, we often reach a point where basic input-output programs, while fundamental, no longer spark the same excitement. The true power of programming shines when our applications interact with the outside world, pulling in dynamic data to solve real-world problems. This tutorial will guide you through building a command-line weather application in Python that does exactly that: fetches current weather data from the internet based on a city name you provide.

This project is an excellent stepping stone for anyone looking to get comfortable with APIs (Application Programming Interfaces). Simply put, an API is a standardized way for your program to communicate with another program to request or send information. Our weather app will take a city name from the terminal, query a weather API, and display the current temperature and wind speed. It's a practical way to learn about making HTTP requests, parsing JSON data, implementing robust error handling, and processing command-line arguments.

By the end of this guide, you'll have a functional script that you can use directly from your terminal, equipped with the knowledge to integrate external data into your Python projects.

Getting Started: Prerequisites

Before diving into the code, ensure you have the following in place:

  • Python: A recent version of Python installed on your system.
  • Code Editor: A text or code editor of your choice (VS Code is a popular option).
  • requests library: This powerful library simplifies making HTTP requests in Python. If you don't have it, install it via pip: python pip install requests

From City Name to Geographic Coordinates

Most weather APIs operate on geographic coordinates (latitude and longitude) rather than city names directly. Therefore, our first step is to translate a user-provided city name, like "London" or "Tokyo," into its corresponding coordinates. For this, we'll leverage Open-Meteo's free geocoding API.

The get_coordinates function handles this conversion: python import requests

def get_coordinates(city_name): url = "https://geocoding-api.open-meteo.com/v1/search" params = { "name": city_name, "count": 1 } response = requests.get(url, params=params, timeout=5) response.raise_for_status() data = response.json() if not data.get("results"): return None latitude = data["results"][0]["latitude"] longitude = data["results"][0]["longitude"] return latitude, longitude

In this function, we construct a URL and a dictionary of parameters for the API call. requests.get() sends an HTTP GET request to the geocoding API. We include a timeout of 5 seconds to prevent the request from hanging indefinitely. response.raise_for_status() is crucial for error handling; it raises an HTTPError for bad responses (4xx or 5xx client/server errors). The response.json() method then parses the JSON response into a Python dictionary.

We check data.get("results") to see if the API returned any matches for the city. If no results are found, the function returns None. Otherwise, it extracts the latitude and longitude from the first result. A small caveat: some city names are common, and this approach simply picks the first match. For production systems, you might want to offer users a choice if multiple cities match.

Fetching the Current Weather Data

With the coordinates in hand, we can now make the actual request for weather information. Open-Meteo also provides a forecast API that we'll use.

The get_weather function takes the latitude and longitude and retrieves the current conditions: python def get_weather(latitude, longitude): url = "https://api.open-meteo.com/v1/forecast" params = { "latitude": latitude, "longitude": longitude, "current": "temperature_2m,wind_speed_10m" } response = requests.get(url, params=params, timeout=5) response.raise_for_status() data = response.json() return data["current"]

Similar to the geocoding function, we build a URL and parameters. The current parameter is key here; by setting it to "temperature_2m,wind_speed_10m", we specifically request the temperature at 2 meters above ground and wind speed at 10 meters. This tells the API to provide only the current conditions for these metrics, rather than a multi-day forecast. After receiving and parsing the JSON response, we return the "current" dictionary, which contains our desired weather metrics.

Building the Command-Line Interface

To make our application user-friendly and runnable from the terminal, we'll integrate the Python sys module. This allows us to access command-line arguments passed to the script.

Here's the main function that orchestrates the entire process: python import sys

def main(): if len(sys.argv) < 2: print("Usage: python weather.py <city_name>") return city = " ".join(sys.argv[1:]) try: coordinates = get_coordinates(city) if not coordinates: print(f"City not found: {city}") return latitude, longitude = coordinates weather = get_weather(latitude, longitude) print(f" Weather in {city.title()}") print(f"Temperature: {weather['temperature_2m']}°C") print(f"Wind speed: {weather['wind_speed_10m']} km/h") except requests.exceptions.RequestException: print("Couldn't connect to the weather service. Check your internet connection and try again.") except (KeyError, ValueError): print("Something went wrong while reading the weather data.")

if name == "main": main()

Let's break down the main function:

  1. Argument Parsing: sys.argv is a list containing all command-line arguments. sys.argv[0] is the script name (weather.py), and subsequent elements are the arguments. We check len(sys.argv) < 2 to ensure a city name was provided. If not, we print a usage message.
  2. Handling Multi-Word City Names: " ".join(sys.argv[1:]) is a clever way to reassemble multi-word city names (e.g., "New York") that would otherwise be split across multiple sys.argv elements.
  3. Orchestration and Error Handling: The core logic is wrapped in a try...except block for robust error management.
    • It calls get_coordinates() with the provided city. If None is returned, it indicates the city wasn't found.
    • If coordinates are retrieved, get_weather() is called.
    • Finally, the extracted temperature and wind speed are printed in a user-friendly format.
    • requests.exceptions.RequestException catches network-related errors (e.g., no internet connection). KeyError and ValueError catch issues that might arise if the API response structure is unexpected or data types are incorrect.

The if __name__ == "__main__": block ensures that main() is called only when the script is executed directly, not when imported as a module.

Testing Your Weather App

Save the entire code into a file named weather.py. Open your terminal or command prompt, navigate to the directory where you saved the file, and try running it with a few different cities:

bash python weather.py Madrid python weather.py Paris python weather.py Washington

An example output might look like this: plaintext Weather in Madrid Temperature: 15.2°C Wind speed: 8.4 km/h

If you forget to supply a city name, the script will guide you on its proper usage: Usage: python weather.py <city_name>.

Potential Enhancements

Once you have the basic application working, consider these straightforward improvements to deepen your understanding and add more features:

  • Add More Data: Include humidity (relative_humidity_2m) or other parameters available from the API.
  • Short Forecast: Modify the current parameter to fetch a short-term forecast instead of just immediate conditions.
  • Ambiguous City Selection: For city names that yield multiple geocoding results, present a numbered list and let the user choose the correct one.
  • Improved Output: Use libraries like rich or f-strings with more formatting to make the output aesthetically pleasing.

The key is to implement one small feature at a time, test it thoroughly, and then move on. This iterative approach helps keep the development process manageable and less prone to overwhelming issues.

Practical Takeaways

This command-line weather app is more than just a simple script; it's a condensed lesson in essential software development practices. You've gained hands-on experience with:

  • Working with APIs: Making external HTTP requests and understanding API documentation.
  • Data Parsing: Extracting relevant information from JSON responses.
  • Modular Design: Using functions to organize code and improve readability.
  • Error Handling: Building robust applications that gracefully handle network issues or unexpected data.
  • Command-Line Arguments: Creating interactive scripts that respond to user input.

To truly internalize these concepts, I highly recommend rebuilding this application from scratch without referencing the provided code. You'll inevitably encounter minor hiccups and errors – these are precisely the moments where real learning happens. Debugging your own mistakes solidifies your understanding far more effectively than merely copying solutions. Once you're comfortable, try applying the same principles to integrate with an entirely different API, perhaps for movie data, cryptocurrency prices, or sports scores. The underlying patterns for API interaction remain largely consistent.

FAQ

Q: Why do weather APIs often require latitude and longitude instead of city names?

A: Geographic coordinates (latitude and longitude) provide a precise and unambiguous location. City names can be less specific; a single city name might refer to multiple locations worldwide, or its boundaries might be vague. Using coordinates ensures that the API returns weather data for the exact point requested, eliminating ambiguity.

Q: What is the purpose of response.raise_for_status() in the requests library?

A: response.raise_for_status() is a convenient method that checks if the HTTP response status code indicates an error (i.e., it's a 4xx client error or 5xx server error). If an error status code is detected, it raises an HTTPError. This simplifies error handling by allowing you to catch network or API-side issues in a try...except block without manually checking the status code for every request.

Q: How does the script handle city names with spaces, like "New York"?

A: The sys.argv list contains each word from the command line as a separate element. For a city like "New York," sys.argv would be ['weather.py', 'New', 'York']. The expression " ".join(sys.argv[1:]) efficiently joins all elements from the second one onwards (skipping the script name) back into a single string, separated by spaces. This reconstructs "New York" from ['New', 'York'], allowing get_coordinates to receive the full city name.

#python#cli#api#requests-library#error-handling

Related articles

ICE's Covert Anti-Left Surveillance Operations Uncovered
Tech
WiredOct 28

ICE's Covert Anti-Left Surveillance Operations Uncovered

New evidence reveals ICE is running a vast, potentially unconstitutional surveillance operation against left-wing activists nationwide. Leveraging post-9/11 tools and extensive data, experts liken it to a 'COINTELPRO 2.0,' marking an unprecedented scale of domestic spying.

Building Passkey Authentication with WebAuthn, Next.js, and NestJS
Programming
freeCodeCampOct 28

Building Passkey Authentication with WebAuthn, Next.js, and NestJS

Password-based authentication has long been the default for digital identity, yet it presents a myriad of challenges for both users and developers. Users grapple with remembering complex passwords, often resorting to

Warhorse Studios Under Siege: Cyberattack Hits Kingdom Come Dev
Games
GamesIndustry.bizOct 27

Warhorse Studios Under Siege: Cyberattack Hits Kingdom Come Dev

Warhorse Studios, known for Kingdom Come: Deliverance 2, has been hit by a cyberattack, resulting in unauthorized access to their company systems and data. CEO Martin Frývaldský called it a "serious incident," and the studio is working with cybersecurity experts to investigate. This incident follows similar breaches at Capcom and Rockstar, highlighting a growing industry concern.

How to Stop Google Using Your Gmail & Drive Data for Ads
How To
LifehackerOct 27

How to Stop Google Using Your Gmail & Drive Data for Ads

Google's "Personal Intelligence" feature, designed to offer more tailored AI responses, may inadvertently lead to your personal data from apps like Gmail, Google Drive, and Google Photos being used for targeted

Java's Enduring Foundations: Interconnectedness, Reliability, and
Programming
Stack Overflow BlogOct 28

Java's Enduring Foundations: Interconnectedness, Reliability, and

Java's origins, driven by creator James Gosling at Sun Microsystems, addressed critical challenges in early computing. The language tackled significant 'networking friction' to enable seamless interconnectedness across diverse systems. Simultaneously, the 'stringent reliability requirements' of consumer electronics inspired the robust design of the Java Virtual Machine (JVM) and its evolving garbage collectors, crucial for 'large-scale concurrent memory management.'

AI Optimism Meets Backlash at Seattle AI Week Kickoff
Tech
GeekWireOct 27

AI Optimism Meets Backlash at Seattle AI Week Kickoff

Seattle AI Week kicked off Monday amidst a striking display of both technological optimism and fervent protest, as climate activists disrupted the event to condemn the rapid expansion of data centers. While tech and

Back to Newsroom

Stay ahead of the curve

Get the latest technology insights delivered to your inbox every morning.