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

十进制转任意进制函数开发及UnboundLocalError错误修复求助

Fixing UnboundLocalError & Perfecting Decimal-to-Arbitrary-Base Function

Let's break down what's going wrong with your code and fix it step by step:

First: Why the UnboundLocalError?

The error happens because the variable x is only defined inside the if 2<=radix<=16 block. If your code hits any other branch (like invalid radix, or n<=0), x never gets created—but you still try to use it in the final print statement. That's Python telling you "I don't know what x is here!"

Other Key Issues in Your Code

  • Incorrect loop logic: Your while int(n/radix) == 0 condition will only run once, which won't handle numbers that need multiple divisions (like 61 → 3*16 +13, so you need two steps).
  • Unused replace_base result: You call replace_base(x) but don't assign the returned string back to x, so the letter replacements (13→D, etc.) never take effect.
  • Wrong format specifiers: You use %d (for integers) to print x, but x is a string (like "3D"). Also, you're passing string inputs n1/radix1 to %d—better to use the converted int values n/radix.
  • Redundant replacement: Your replace_base has a replace('16', 'G') line, but since radix maxes out at 16, the remainder can never be 16 (max remainder is 15 for radix 16).
  • Incomplete input handling: No check for non-numeric inputs, and the error messages are vague.

Fixed Code

def replace_base(x):
    # Remove the unnecessary '16' → 'G' replacement
    x = x.replace('10', 'A')
    x = x.replace('11', 'B')
    x = x.replace('12', 'C')
    x = x.replace('13', 'D')
    x = x.replace('14', 'E')
    x = x.replace('15', 'F')
    return x

def deci_to_any_list():
    # Add input validation for numeric values
    try:
        n1 = input("Enter a positive integer: ")
        n = int(n1)
        radix1 = input("Enter a radix (2-16): ")
        radix = int(radix1)
    except ValueError:
        print("Error: Please enter valid integers!")
        return

    converted_number = []

    if n <= 0:
        print("Wrong input!! The number must be a positive integer.")
        return

    if not (2 <= radix <= 16):
        print(f"Wrong input!! Radix must be between 2 and 16 (inclusive), you entered {radix}.")
        return

    # Correct loop logic: keep dividing until n becomes 0
    temp_n = n
    while temp_n > 0:
        remainder = temp_n % radix
        converted_number.append(str(remainder))  # Store as string to avoid later conversion
        temp_n = temp_n // radix  # Use integer division

    # Reverse the list and join into a string
    converted_number.reverse()
    x = ''.join(converted_number)
    # Assign the replaced result back to x
    x = replace_base(x)

    # Use correct format specifiers: %d for integers, %s for the hex-like string
    print("%d in base 10 is %s in base %d" % (n, x, radix))

deci_to_any_list()

What Changed & Why?

  1. Input validation with try-except: Catches cases where users enter non-numeric values, preventing ValueError when converting to int.
  2. Early returns for invalid inputs: Ensures we never reach the print statement with undefined variables—if input is invalid, we print an error and exit the function early.
  3. Fixed loop logic: We use a temp_n variable to preserve the original n (for the final print), and loop while temp_n > 0—this correctly collects all remainders.
  4. Stored remainders as strings: Saves us from converting each integer to string later when joining.
  5. Assigned replace_base output: x = replace_base(x) ensures the letter replacements are actually applied.
  6. Corrected format string: Used %s for x since it's a string (like "3D"), and used the int values n/radix instead of the input strings.
  7. Clearer error messages: Tells users exactly what's wrong (e.g., radix out of range, non-positive number).

Testing your example input (61, 16) will now output:

61 in base 10 is 3D in base 16

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:27:52