十进制转任意进制函数开发及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) == 0condition 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 tox, so the letter replacements (13→D, etc.) never take effect. - Wrong format specifiers: You use
%d(for integers) to printx, butxis a string (like "3D"). Also, you're passing string inputsn1/radix1to%d—better to use the converted int valuesn/radix. - Redundant replacement: Your
replace_basehas areplace('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?
- Input validation with try-except: Catches cases where users enter non-numeric values, preventing
ValueErrorwhen converting to int. - 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.
- Fixed loop logic: We use a
temp_nvariable to preserve the originaln(for the final print), and loop whiletemp_n > 0—this correctly collects all remainders. - Stored remainders as strings: Saves us from converting each integer to string later when joining.
- Assigned
replace_baseoutput:x = replace_base(x)ensures the letter replacements are actually applied. - Corrected format string: Used
%sforxsince it's a string (like "3D"), and used the int valuesn/radixinstead of the input strings. - 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
相关产品推荐
相关产品推荐

