I have written a python 2 program for a school project to convert from hexadecimal to decimal without using built-in functions and vice versa in python. I would like to know how I can make my code more concise - specifically, the "d_func" function.
d_dict = {"0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, "7" : 7, "8" : 8, "9" : 9, "A" : 10, "B" : 11, "C" : 12, "D" : 13, "E" : 14, "F": 15}
def d_func(digit, mode):
if mode == 1:
for x in range(len(d_dict.keys())):
if digit == list(d_dict.keys())[x]:
return x
else:
for y in range(len(d_dict.values())):
if digit == list(d_dict.values())[y]:
return list(d_dict.keys())[y]
def hd_func(h_num):
d_num, p = 0, 0
for digit in range(len(h_num), 0, -1):
d_num = d_num + 16 ** p * d_func(h_num[digit - 1], 1)
p += 1
return str(d_num)
def dh_func(d_num):
f_list, h_num, p = [], "", 0
while d_num > 0:
f_list.append(d_num % 16)
d_num //= 16
for f in f_list[::-1]:
h_num += d_func(f, 2)
return h_num
func_dict = {"h": hd_func, "d": dh_func}
u_choice, u_num = input("Enter [H] for Hexadecimal to Decimal, [D] for Decimal to Hexadecimal"), input("Enter the number: ")
print(func_dict[u_choice.lower()](u_num))
python-3.x
in the future, aspython-2.x
has reached it's end of life. \$\endgroup\$python-3.x
. :) \$\endgroup\$