You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求排查Python二进制转十进制代码错误(Python入门1个月)

Binary to Decimal Converter: Fixing Your Python Code

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 n in the loop
    When you do z = n%10, you're grabbing the last digit of the original number every time. Without modifying n (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 calculate k = z*power but never use it—instead, you just add z (the digit itself) to ans. 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 uses lenf, 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:

  1. reversed() + enumerate()
    Reversing the binary string lets us start counting powers of 2 from 0 (the rightmost bit, which is 2⁰). enumerate gives us both the index (used for the exponent) and the digit itself.

  2. 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.

  3. 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 while loop to keep processing digits until the number is reduced to 0
  • Updating binary_num with // 10 to remove the last digit after processing it
  • Actually adding the weighted value (z * 2**power) to ans instead of just the digit itself

内容的提问来源于stack exchange,提问作者AbhishekTailor700

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:34:11