natural number to bin in python

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.py
n = 10
binary = format(n, 'b')
print(binary)
45 chars
4 lines

Output:

main.py
1010
5 chars
2 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.py
binary = '1010'
n = int(binary, 2)
print(n)
44 chars
4 lines

Output:

main.py
10
3 chars
2 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