I'm trying to write a function in Python that will convert numbers into different bases. I created a while loop that should turn any number into a base 10 number. My plan is to convert the first number into base 10, then convert that into the target base. I'm doing it that way because all the arithmetic must be done in base 10.
I mapped out a flow chart and put the code in, but it always puts out the same result and I don't know why.
Here's my code:
def fconbase(cnum, cbase1, cbase2):
#resets variables used in calculations
exp=0
result=0
decimalResult=0
currentDigit="blank"
cnumlen=len(str(cnum)) #finds length of cnum, stays constant
digitNum=cnumlen #sets starting placement
while exp<cnumlen:
currentDigit=str(cnum)[digitNum-1:digitNum]
#the following converts letters into their corresponding integers
if currentDigit=="a" or "A":
currentDigit="10"
if currentDigit=="b" or "B":
currentDigit="11"
if currentDigit=="c" or "C":
currentDigit="12"
if currentDigit=="d" or "D":
currentDigit="13"
if currentDigit=="e" or "E":
currentdigit="14"
if currentDigit=="f" or "F":
currentDigit="15"
result=int(currentDigit)
decimalResult=decimalResult+result*(10**exp)
exp=exp+1
digitNum=digitNum-1
print(decimalResult)
Here's how it should work:
First, it finds how many digits are in the original number. That is used to determine how many times the loop should continue.
Then it uses that to fish out the final digit. Next, it converts any letters into their appropriate digits (this is for if the number is in base 11 or higher). It turns that into an integer and multiplies it by 10^exp. The exp starts at 0, so 10^exp should come out to 1.
Then, it adds the result to the decimalResult (the result in base 10). Then it increases the exp(onent) by 1 so that 10**exp will now come out to 10 and subtracts one from the 'currentDigit' to fish out the second to last digit.
Then it loops around and continues this pattern until the exp is equal to the cnumlen (length of the starting number) and prints the final result.
I don't know where my formula is messing up. I don't see any logic errors in it that would result in this. I've been messing around with it for hours and can't get it to do anything different. Well, at first it was throwing out numbers that I had no clue where it was getting them. After messing around, now it just throws out the same number over and over. I can't figure out where its getting any of these numbers.