Binary to Decimal Conversion Program in Python
This guide explains how to write a Python program to convert binary numbers to decimal numbers. The program is structured with clear documentation for each part of the code.
Program Structure and Explanation
The program consists of the following parts:
- Function to convert a binary string to a decimal number
- Main block to take input and display the result
- Documentation for each part of the code
Python Code
# Function to convert binary to decimal
def binary_to_decimal(binary_str):
"""
Convert a binary string to a decimal number.
Parameters:
binary_str (str): A string representing a binary number (e.g., "1010").
Returns:
int: The decimal representation of the binary number.
"""
decimal_number = 0
for index, digit in enumerate(binary_str[::-1]):
if digit == '1':
decimal_number += 2 ** index
return decimal_number
# Main block
if __name__ == "__main__":
"""
Main block to take binary input from the user and print the decimal output.
"""
# Taking binary input from the user
binary_input = input("Enter a binary number: ")
# Validating the input
if all(char in '01' for char in binary_input):
# Converting binary to decimal
decimal_output = binary_to_decimal(binary_input)
print(f"The decimal representation of binary {binary_input} is {decimal_output}.")
else:
print("Invalid binary number. Please enter a binary number containing only 0s and 1s.")
Explanation
Function: binary_to_decimal
The binary_to_decimal
function converts a binary string to a decimal number. Here is how it works:
- Initialization: A variable
decimal_number
is initialized to 0. This variable will store the final decimal number. - Iteration: The function iterates over the binary string in reverse order (using
enumerate
to get both the index and the digit). - Conversion: For each ‘1’ in the binary string, the function adds
2
raised to the power of the index todecimal_number
. - Return: The function returns the calculated decimal number.
Main Block
The main block of the program does the following:
- Input: Takes a binary number as input from the user.
- Validation: Checks if the input string contains only ‘0’ and ‘1’. If not, it prints an error message.
- Conversion: Calls the
binary_to_decimal
function to convert the binary string to a decimal number. - Output: Prints the decimal representation of the binary number.
This program provides a simple and effective way to convert binary numbers to decimal using Python, with clear documentation for better understanding and maintainability.