I was very pleased to learn the "enumerate()" function - thanks Blackjack for this!
I have now used this in my "to-denary" function and I think it is a lot better that my previous version.
I know this program could really do with some checking of input /error handling, but I am quite pleased with how it works so far ...
- Code: Select all
# bases.py - converts a base to another base.
import math
def to_denary(n, b, D):
"""Converts to denary."""
denary = 0
for i in enumerate(reversed(n)):
temp = D.index(i[1])
denary += temp * math.pow(b, i[0])
return denary
def to_base(n, b, D):
"""Converts n to base b."""
result = ""
while n != 0:
temp = int(n % b)
n //= b
result = D[temp] + result
return result
def main():
DIGITS = "0123456789ABCDEF"
print("**** Base conversion ***")
base_a = input("Base of input:" )
while base_a != "":
base_a = int(base_a)
base_b = int(input("Base for output: "))
num = input("Number: ")
ans = to_base((to_denary(num, base_a, DIGITS)), base_b, DIGITS)
print("The base", base_a, "number", num, "in base", base_b, "is", ans)
base_a = input("Base of input:" )
# call main
main()
At some point I want to make a GUI version.
Here's a sample run: