calculate binary number from dec in python

You can use the built-in bin() function in Python to convert a decimal number to its equivalent binary representation. The function takes the decimal number as an argument and returns a string that represents the corresponding binary number.

Here's an example:

main.py
decimal_num = 10
binary_num = bin(decimal_num)

print(binary_num)  # Output: 0b1010
84 chars
5 lines

In this example, we convert the decimal number 10 to binary using the bin() function. The result is a string 0b1010, where the prefix 0b indicates that it's a binary representation.

Alternatively, you can also use the string format() method with the format specifier b to convert a decimal number to binary. Here's an example:

main.py
decimal_num = 10
binary_num = "{0:b}".format(decimal_num)

print(binary_num)  # Output: 1010
93 chars
5 lines

In this example, we use the string format() method with the format specifier b to convert the decimal number 10 to binary. The result is a string 1010 representing the binary number.

gistlibby LogSnag