baseconverter.py

Created by matt-numworks

Created on October 24, 2025

1.65 KB


# Type your text here
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

#while loop to repeat
while True:
  # 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)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.