Binary to Decimal Converter in Python.
About the project: This program will allow you to enter a binary number (a sequence of 1s and 0s), and it will convert it into its decimal equivalent.
It will run in a continuous loop, so you can perform multiple conversions without restarting the program.
This program will conver a number from Binary to Decimal.
How to use this Binary to Decimal Converter:
- Run the Python script.
- When you run it, you can enter any binary number.
- It will immediately convert it to its decimal form.
- The program will continue to run until you type q to quit.
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# binary_to_decimal_converter.py
def binary_to_decimal(binary_string):
"""
Converts a binary string to its decimal integer equivalent.
Args:
binary_string (str): A string containing only '0's and '1's.
Returns:
int: The decimal equivalent of the binary string.
"""
decimal_value = 0
power = 0
# Iterate through the binary string from right to left
# This is equivalent to `binary_string[::-1]`
for digit in reversed(binary_string):
if digit == '1':
# Add 2 raised to the power of its position
decimal_value += 2 ** power
power += 1
return decimal_value
def is_valid_binary(binary_string):
"""
Checks if a string contains only '0's and '1's.
"""
return all(char in '01' for char in binary_string)
def main():
"""
Main function to run the Binary to Decimal Converter in a continuous loop.
"""
print("--- Python Binary to Decimal Converter ---")
print("Enter a binary number (e.g., 1010) or 'q' to quit.")
while True:
user_input = input("\nEnter a binary number: ").strip()
# Check if the user wants to quit
if user_input.lower() == 'q':
print("Exiting Binary to Decimal Converter. Goodbye!")
break
# Check for empty input
if not user_input:
print("Please enter a binary number.")
continue
# Validate the input
if is_valid_binary(user_input):
decimal_result = binary_to_decimal(user_input)
print(f"The decimal equivalent of {user_input} is {decimal_result}.")
else:
print("Invalid input. Please enter a number containing only 1s and 0s.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()