This script will take a number in any base (2-16), and convert it to another base (2-16).
Method: First, it converts all numbers (regardless of the goal) to base 10. Then it will either return the base 10 value it that is the goal, or converts to the target base.
Because a crucial part of this script is to convert all numbers to base 10, the script will return the base 10 conversion AND the desired conversion, if base 10 is not the goal nor the initial base.
This script has two functions defined, convert_to_10 and convert_from_10. These two functions are helper functions that do the mathematical computation converting numbers to and from base 10.
# Function to convert number (s) from the given base (2–16) to base 10. def convert_to_10(s, base): digits = "0123456789ABCDEF" s = s.upper() value = 0 # Check user input is valid number in base for character in s: if character not in digits[:base]: print("Invalid digit '{}' for base {}".format(character, base)) return None value = value * base + digits.index(character) return value # Function to convert number (n) from base 10 to the given base (2–16). def convert_from_10(n, base): if n == 0: return "0" digits = "0123456789ABCDEF" result = "" while n > 0: result = digits[n % base] + result n //= base return result # Prompts for user input print("Universal Base Converter") num_start = input("Enter the number: ") from_base = int(input("Convert from base (2-16): ")) to_base = int(input("Convert to base (2-16): ")) # Check user input is valid base if from_base < 2 or from_base > 16 or to_base < 2 or to_base > 16: print("Base must be between 2 and 16") else: # Convert all numbers to base 10 base_10 = convert_to_10(num_start, from_base) if base_10 is not None: # Only show Base 10 value if it's not redundant if from_base != 10 and to_base != 10: print("Base 10 value:", base_10) # Compute and display the final result if to_base == 10: # No need to reconvert; just show base 10 value result = str(base_10) else: result = convert_from_10(base_10, to_base) print("Result:", result)