Input a number in binary format in python

 


In Python, you can input a number in binary format using the `int` function with base.

Input a number in binary format in python

binary_number = input(“Enter a binary number: “)

decimal_number = int(binary_number, 2)

print(“Decimal equivalent:”, decimal_number)

1. `input(“Enter a binary number: “)`: This prompts the user to enter a binary number as a string.

2. `int(binary_number, 2)`: Converts the `binary_number` string from binary (base 2) to a decimal integer.

– The second argument `2` specifies that `binary_number` is in base 2 (binary).

3. `print(“Decimal equivalent:”, decimal_number)`: Outputs the decimal equivalent of the binary number entered by the user.

For example, if you enter `”1010″`, the output will be `10` (since binary `1010` equals decimal `10`).

4. **Using `int()` function:** The `int()` function in Python converts a string (or another number) to an integer. When you pass a string representing a number in a specific base (like binary, octal, decimal, or hexadecimal), you can specify that base as the second argument.

4. **Input from User:**

If you want to take binary input from a user and convert it to a decimal number, you can use the `input()` function to get the binary string from the user:

5. **Handling Invalid Input:**

– If the input string contains characters that are not valid in the specified base (e.g., characters other than `0` or `1` in binary), `int()` will raise a `ValueError`. You might want to handle this with a try-except block or validate the input beforehand.

6. **Conversion to Other Bases:**

– Similarly, you can use `bin()`, `oct()`, or `hex()` functions to convert a decimal number to binary, octal, or hexadecimal, respectively.

Binary_number = input("Enter a binary number: ")
decimal_number = int(binary_number, 2)
print("Decimal equivalent:", decimal_number)

Output 
Enter the number 1010
Decimal number is 10

 

Scroll to Top