Hello Africoders and fellow computing students! This semester, Python has become my new playground, and as part of our coursework, our lecturer assigned us a group project. My group and I chose to create a practical and exciting project—a real-time currency converter. In this blog post, I
**Step 1: Creating the Project Folder
First, I created a new folder for my project and opened it in Visual Studio Code (VSCode). This is where I organized all the project files.
**Step 2: Setting Up a Virtual Environment
To keep the project dependencies isolated and manageable, I created a virtual environment. Here’s how you can do it:
**Open a terminal in VSCode.
Run the following command to create a virtual environment:
`python -m venv venv
**Activate the virtual environment:
**On Windows:
```
`venv\Scripts\activate`
```
**On macOS/Linux:
```
`source venv/bin/activate`
```
**Step 3: Installing Necessary Libraries
I needed a couple of libraries to make the program work:
**You can install requests using pip:
`pip install requests
**Getting the API Key
To get real-time currency exchange rates, I signed up on CurrencyAPI and obtained an API key. This key allows me to access the currency conversion data provided by the service.
**Go to CurrencyAPI
**Sign up for a free account
Once you have signed up, you will find your API key in the dashboard.
**Understanding the Code Logic
My currency converter fetches exchange rates from the CurrencyAPI and calculates the converted amount based on user input. Here’s the pseudo-code for the program:
**The Code
Here’s the actual implementation of the program:
**Code Explanation
Importing Libraries:
`import sys` import requests
**Defining Constants:
`API_KEY = 'YOUR_API_KEY'
` BASE_URL = 'https://api.currencyapi.com/v3/latest'
**Defining the get_exchange_rate Function
def get_exchange_rate(base_currency, target_currency):
```
url = f"{BASE_URL}?apikey={API_KEY}&base_currency={base_currency}¤cies={target_currency}"
try:
response = requests.get(url)
response.raise_for_status() # Check if request was successful
data = response.json()
if 'data' in data and target_currency in data['data']:
return data['data'][target_currency]['value']
else:
print(f"Invalid currency: {target_currency}")
sys.exit(1)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
sys.exit(1)
```
Constructs the API request URL using the base currency and target currency.
Makes a GET request to the API.
Parses the JSON response and returns the exchange rate.
**Defining the main Function:
`def main():
` base_currency = input("Enter the base currency (e.g., USD): ").strip().upper()
` target_currency = input("Enter the target currency (e.g., EUR): ").strip().upper()
` try:
` amount = float(input("Enter the amount: "))
` except ValueError:
` print("Invalid amount. Please enter a numeric value.")
` sys.exit(1)
` rate = get_exchange_rate(base_currency, target_currency)
` if rate is None:
` print(f"Could not find exchange rate from {base_currency} to {target_currency}")
` sys.exit(1)
` converted_amount = amount * rate
` print(f"{amount} {base_currency} is equivalent to {converted_amount:.2f} {target_currency}")
`` `
Running the Main Function:
`if __name__ == "__main__":
` main()
Ensures that the main function is executed when the script is run directly.
## Challenges and Solutions
### 1. **No Internet Connection**
**Error
**Solution`requests.exceptions.RequestException
### 2. **Invalid Currency Code**
**Error
**Solution
### 3. **Invalid Amount Input**
**Error
**Solution`ValueError
## Conclusion
This project was a fantastic learning experience for me. I learned how to interact with APIs, handle exceptions, and develop a user-friendly CLI application.
What do you think of my approach? Do you have any suggestions for improving the code? I’d love to hear your thoughts and ideas on how to make this project even better. Let’s keep coding and learning together!
Happy coding, Africoders and my fellow computing students!