Don't use recursion in this case. Python doesn't optimize tail recursion and after long session script can show your RuntimeError: maximum recursion depth exceeded
.
Don't use floating point arithmetic in this case. Use decimal arithmetic with decimal module. For example:
>>> 100 * 2.2
220.00000000000003
>>> from decimal import Decimal
>>> Decimal("100") * Decimal("2.2")
Decimal('220.0')
Split logic and presentation. For now there is no way to use this converter with Web UI or as a library for a bigger program. For example you can start with low level functions like this:
def kilograms_to_pounds(amount):
return amount * Decimal("2.2")
def pounds_to_kilograms(amount):
return amount / Decimal("1.45")
Then you can create front-end function like this:
converters = {
("kilograms", "pounds"): kilograms_to_pounds,
("pounds", "kilograms"): pounds_to_kilograms,
}
def convert(amount, from_, to):
c = converters.get((from_, to))
if c is None:
raise ValueError("converter not found")
return c(amount)
>>> convert(Decimal("100"), "pounds", "kilograms")
Decimal('68.96551724137931034482758621')
Later you can add aliases like this (or as function decorator):
aliases = {
"kg": "kilograms",
"lb": "pounds",
...
}
def convert(amount, from_, to):
from_ = aliases.get(from_, from_)
to = aliases.get(to, to)
c = converters.get((from_, to))
if c is None:
raise ValueError("converter not found")
return c(amount)
>>> convert(Decimal("100"), "lb", "kg")
Decimal('68.96551724137931034482758621')
With this architecture you can later add other converters to your library and you need to call only convert()
function from your UI loop.
Also I don't like your UI. For example if I need to convert 10 values from kilograms to pounds I need to enter value then I need to enter "kilograms". By adding modes to your converter you can save me 10 lines. For example user first enter "kilograms to pounds" and this conversion mode stored and displayed in the prompt. Then user can enter values which will be converted from kilograms to pounds. Later user can change conversion mode by entering "pounds to kilograms".