请求排查Python二进制转十进制代码错误(Python入门1个月)
Hey there! Since you're only a month into Python—awesome work tackling this problem already! Let's break down the issues in your code and fix them up so it correctly converts binary numbers to decimal.
What's Wrong with the Original Code?
Let's go through the key issues one by one:
You never update the value of
nin the loop
When you doz = n%10, you're grabbing the last digit of the original number every time. Without modifyingn(like removing the last digit), you'll keep processing the same digit over and over instead of moving left to the next bit.You're adding the wrong value to
ans
You calculatek = z*powerbut never use it—instead, you just addz(the digit itself) toans. That means your result will be the sum of all binary digits, not their weighted value based on powers of 2 (which is how binary-to-decimal conversion works).Over-reliance on global variables
Your function useslenf, a variable defined outside the function. While this isn't a critical error, it's better practice to keep functions self-contained so they're easier to reuse and debug.
Fixed Version (String-Based Approach)
This version uses string handling for clarity, which is great for beginners to follow:
def binary_to_decimal(binary_input): decimal_value = 0 # Reverse the binary string to start from the least significant bit (rightmost) for index, digit in enumerate(reversed(binary_input)): # Calculate the weight: 2 raised to the index position weight = 2 ** index # Add the digit's contribution to the total decimal value decimal_value += int(digit) * weight return decimal_value # Get user input user_input = input("Enter the binary number: ") # Optional: Validate the input is actually binary (only 0s and 1s) if all(char in "01" for char in user_input): print(f"Decimal equivalent: {binary_to_decimal(user_input)}") else: print("Oops! Please enter a valid binary number (only 0s and 1s).")
Key Fixes Explained:
reversed()+enumerate()
Reversing the binary string lets us start counting powers of 2 from 0 (the rightmost bit, which is 2⁰).enumerategives us both the index (used for the exponent) and the digit itself.Proper weighted addition
We convert each digit to an integer, multiply it by its corresponding power of 2, and add that to the total decimal value—this is the core of binary-to-decimal conversion.Input validation
Added a check to ensure the user only enters 0s and 1s, which prevents errors from invalid inputs.
Alternative Version (Integer Operations)
If you prefer working with integers instead of strings (closer to your original approach), here's a fixed version:
def calculate(binary_num): ans = 0 power = 0 while binary_num > 0: # Grab the last digit z = binary_num % 10 # Add the weighted value to ans ans += z * (2 ** power) # Remove the last digit from the number binary_num = binary_num // 10 # Increment the power for the next digit to the left power += 1 print(f"Decimal equivalent: {ans}") # Get user input n = int(input("Enter the binary number: ")) # Validate input is binary if all(digit in "01" for digit in str(n)): calculate(n) else: print("Invalid input! Please enter a binary number.")
This fixes your original loop by:
- Using a
whileloop to keep processing digits until the number is reduced to 0 - Updating
binary_numwith// 10to remove the last digit after processing it - Actually adding the weighted value (
z * 2**power) toansinstead of just the digit itself
内容的提问来源于stack exchange,提问作者AbhishekTailor700

