IOS Programmer - 9 months ago 82

Python Question

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")

binary_list=["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"]

print("binary list")

hex_list=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]

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")

count1=0

while count1<len(denarylist) and count1<len(binarylist) and count1<len(hexlist):

print(denarylist[count1],"\t",binarylist[count1],"\t",hexlist[count1])

count1+=1

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')
'10011010010'
>>> format(1234, 'x')
'4d2'
```

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 **number**th 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])
```