Mapping numbers to their binary and hexadecimal representations


Creates a dictionary named number_binary_hex using a dictionary comprehension in Python. This dictionary maps numbers from 1 to 10 to their binary and hexadecimal representations. Here's a step-by-step explanation of the code:

  • number_binary_hex = {num: (bin(num)[2:], hex(num)[2:]) for num in range(1, 11)}: This line creates the number_binary_hex dictionary using a dictionary comprehension. Here's how it works:
    • {num: (bin(num)[2:], hex(num)[2:]) for num in range(1, 11)} is the dictionary comprehension. It performs the following steps:
    • for num in range(1, 11) iterates over numbers from 1 to 10 (inclusive).
    • (bin(num)[2:], hex(num)[2:]) is a tuple containing two elements:
      • bin(num)[2:] converts the number num to its binary representation using the bin function and then slices off the first two characters (which represent "0b" at the beginning of the binary string).
      • hex(num)[2:] converts the number num to its hexadecimal representation using the hex function and then slices off the first two characters (which represent "0x" at the beginning of the hexadecimal string).
    • It creates a key-value pair in the dictionary, where the key (num) is the number itself, and the value is the tuple containing the binary and hexadecimal representations.
  • print(number_binary_hex): This line prints the number_binary_hex dictionary to the console.

Source Code

number_binary_hex = {num: (bin(num)[2:], hex(num)[2:]) for num in range(1, 11)}
print(number_binary_hex)

Output

{1: ('1', '1'), 2: ('10', '2'), 3: ('11', '3'), 4: ('100', '4'), 5: ('101', '5'), 6: ('110', '6'), 7: ('111', '7'), 8: ('1000', '8'), 9: ('1001', '9'), 10: ('1010', 'a')}

Example Programs