Python_basic_4
Python_basic_4
Your Name
March 24, 2025
1 Introduction
This document presents a Python-based Currency Converter. The program
fetches real-time exchange rates from an API and converts amounts between
different currencies.
2 Python Code
1 import requests
2
3 API_URL = " https :// api . exchangerate - api . com / v4 / latest / "
4
5 def g e t _ e x c h a n g e _ r a t e ( base_currency , t a rg et _c u rr en cy ) :
6 try :
7 response = requests . get ( API_URL + base_currency )
8 data = response . json ()
9
10 if " rates " in data :
11 return data [ " rates " ]. get ( target_currency , None )
12 else :
13 return None
14 except Exception as e :
15 print ( f " Error fetching exchange rate : { e } " )
16 return None
17
18 def c o n v e r t _ c u r r e n c y () :
19 base_currency = input ( " Enter base currency ( e . g . , USD ) : " ) .
upper ()
20 t ar ge t_ c ur re nc y = input ( " Enter target currency ( e . g . , EUR ) : " ) .
upper ()
21
22 try :
23 amount = float ( input ( " Enter amount to convert : " ) )
24 exchange_rate = g e t _ e x c h a n g e _ r a t e ( base_currency ,
t ar ge t_ c ur re nc y )
25
26 if exchange_rate :
27 c o n v e r t e d _ a m o u nt = amount * exchange_rate
28 print ( f " \ n { amount } { base_currency } = {
c o n v e r t e d _ a m o u n t :.2 f } { ta r ge t_ cu r re nc y }\ n " )
1
29 else :
30 print ( " Exchange rate not found !\ n " )
31 except ValueError :
32 print ( " Invalid amount ! Please enter a number .\ n " )
33
34 def main () :
35 print ( " Welcome to the Currency Converter ! " )
36 while True :
37 print ( " \ n Currency Converter Menu : " )
38 print ( " 1 Convert Currency " )
39 print ( " 2 Exit " )
40
41 choice = input ( " Choose an option (1 -2) : " ) . strip ()
42
43 if choice == " 1 " :
44 c o n v e r t _ c u r r e n cy ()
45 elif choice == " 2 " :
46 print ( " Exiting Currency Converter . Have a great
day !\ n " )
47 break
48 else :
49 print ( " Invalid option ! Please try again .\ n " )
50
51 if __name__ == " __main__ " :
52 main ()