To convert an integer (int) to binary in Python, you can use the built-in bin() function. Here’s how:
# Sample integer number = 10 # Convert integer to binary binary_number = bin(number) # Print the binary representation print(binary_number)
Output:
0b1010
The bin() function takes an integer as an argument and returns its binary representation as a string with a prefix of 0b. In the example above, bin(10) returns the string ‘0b1010’, which represents the binary value of 10.
You can remove the 0b prefix by using string slicing like this:
# Sample integer number = 10 # Convert integer to binary and remove prefix binary_number = bin(number)[2:] # Print the binary representation print(binary_number)
Output:
1010
In this case, the bin() function is called as before, but we use string slicing to remove the first two characters (the prefix ‘0b’) from the returned string. The resulting value, ‘1010’, is the binary representation of 10.