I'm a beginner and it is my first project in Python 2.7.
My goal is writing a script that I can run with two or three arguments.
If run with two arguments like python currency.py RUB USD
then the output will be current RUB rate by USD base: .015169.
If run with three arguments like python currency.py 1000 RUB USD
then it will convert 1000 RUB to dollar.
#!/usr/bin/env python
import ast, requests
import sys, argparse
def checker(base, symbol):
url = "http://api.fixer.io/latest?base=%s" % base.upper()
r = requests.get(url)
content = ast.literal_eval(r.content)
rate = content["rates"][symbol.upper()]
return rate
parser = argparse.ArgumentParser(description = "Currency converter. For instance : 'Convert 100 USD to RUB' Will be: 100 USD RUB. If You need only rate: USD RUB")
if len(sys.argv) > 3:
parser.add_argument("n", type =int, help = "Amount of currency_for_convert", default=1)
parser.add_argument('currency_for_convert', type=str, help="Currency for convert")
parser.add_argument("currency_converted_to", type=str, help = "Currency that converted to")
args = parser.parse_args()
rate = checker(args.currency_for_convert, args.currency_converted_to)
print rate if len(sys.argv) <= 3 else rate*args.n
But I don't like the way I'm using if statements because the running script help ignore third argument and give information only about first two arguments.
$ python currency.py --help usage: currency.py [-h] currency_for_convert currency_converted_to
Currency converter. For instance : 'Convert 100 USD to RUB' Will be: 100 USD RUB. If You need only rate: USD RUB
positional arguments: currency_for_convert Currency for convert
currency_converted_to Currency that converted tooptional arguments: -h, --help show this help message and exit
Is there another way to write two/tree arguments script?