Python bin() Built in Function
The Python bin() function converts an integer number to a binary string prefixed with 0b. For example, the binary equivalent of 2 is 0b10. The result is a valid Python expression.
Here are some examples of using bin() function:
# Example 1: Convert integer to binary with bin() method
num = 10
print(bin(num)) # Output: 0b1010
# Example 2: Convert negative integer to binary with bin() method
num = -5
print(bin(num)) # Output: -0b101
# Example 3: Convert float to binary with bin() method (raises TypeError)
num = 3.14
print(bin(num)) # Output: TypeError: 'float' object cannot be interpreted as an integer
# Example 4: Convert string to binary with bin() method (raises ValueError)
num = "Hello"
print(bin(num)) # Output: ValueError: invalid literal for int() with base 10: 'Hello'
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment