IOS Programmer IOS Programmer - 9 months ago 82
Python Question

Python Denary to Binary Convertor

Hi can you please help me convert denary values to binary and hex? I have to input a number between 0 and 15 and the output should be its hexadecimal and binary equivalent. Here's what I've done so far:

denary_list= ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"]
print("denary list")

print("binary list")

print("hex list")
option=input("enter choice:\n1.print values\n2.convert denary number to binary and hex\n3. Convert a hex value between 0 and 15 to denary or binary value\n9. Quit")
if option=='1':
print ("denary","\t","binary","hex")
while count1<len(denarylist) and count1<len(binarylist) and count1<len(hexlist):
if option=='2':
number=int(input("what number do you choose to convert to binary and hex"))
if number<=15 and number>=0:

Answer Source

Use the format method instead with b and x format codes to format integers as hexadecimal or binary numbers:

>>> format(1234, 'b')
>>> format(1234, 'x')

Use int('01234fff', 16) to convert a hex string into a number; likewise int('11110000', 2) to convert a binary string into a number.

And to answer your original question: you can get numberth item (zero-based indexing) with binary_list[number] and so you can write your option 2 as

number = int(input("what number do you choose to convert to binary and hex"))
if 0 <= number <= 15:
    print("the number in binary is", binary_list[number])
    print("the number in hex is", hex_list[number])