To convert a natural number to binary in Python, you can use the built-in format()
function along with the format specifier b
, which represents binary. Here is an example:
main.py45 chars4 lines
Output:
main.py5 chars2 lines
In the above code, we have assigned the natural number 10
to the variable n
. Then we have used the format()
function to convert n
to binary format and assigned the result to the variable binary
. Finally, we are printing the value of binary
.
You can also convert binary back to a natural number using the int()
function:
main.py44 chars4 lines
Output:
main.py3 chars2 lines
In the above code, we have assigned the binary representation 1010
to the variable binary
. Then we have used the int()
function with the base argument set to 2
to convert binary
back to a natural number and assigned it to the variable n
. Finally, we are printing the value of n
.
gistlibby LogSnag