How to Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal?

Estimated read time 1 min read

Sure! Here’s a Python program that converts a decimal number to its binary, octal, and hexadecimal representations:

decimal = int(input("Enter a decimal number: "))

binary = bin(decimal)
octal = oct(decimal)
hexadecimal = hex(decimal)

print("Binary: " + binary)
print("Octal: " + octal)
print("Hexadecimal: " + hexadecimal)

In this program, the int(input("Enter a decimal number: ")) line prompts the user to enter a decimal number, which is then converted to an integer using the int() function.

The bin(), oct(), and hex() functions are used to convert the decimal number to its binary, octal, and hexadecimal representations, respectively. These functions return strings that represent the converted values.

Finally, the program prints the binary, octal, and hexadecimal representations using the print() function.

Here’s an example output:

Enter a decimal number: 42
Binary: 0b101010
Octal: 0o52
Hexadecimal: 0x2a

The 0b, 0o, and 0x prefixes indicate the number system used for the corresponding representation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply