Number converter – python

# number_converter.py
# Works in Pydroid 3 (Android Python environment)

import inflect

# Create engine for number-to-words
p = inflect.engine()

# Function to convert to Roman numerals
def to_roman(num):
    if not (0 < num < 4000):
        return “Roman numerals only support 1–3999”
    values = [
        (1000, “M”), (900, “CM”), (500, “D”), (400, “CD”),
        (100, “C”), (90, “XC”), (50, “L”), (40, “XL”),
        (10, “X”), (9, “IX”), (5, “V”), (4, “IV”), (1, “I”)
    ]
    result = “”
    for val, symbol in values:
        while num >= val:
            result += symbol
            num -= val
    return result

# Function to convert number to binary
def to_binary(num):
    return bin(num)[2:]

# Function to convert number to hexadecimal
def to_hex(num):
    return hex(num)[2:].upper()

# Function to convert number to words
def to_words(num):
    return p.number_to_words(num)

# Main interactive loop
def main():
    while True:
        try:
            num = int(input(“\nEnter a number (or -1 to quit): “))
            if num == -1:
                print(“Goodbye!”)
                break

            print(“\nChoose conversion:”)
            print(“1. Roman Numerals”)
            print(“2. Binary”)
            print(“3. Hexadecimal”)
            print(“4. Words”)

            choice = input(“Enter choice (1-4): “)

            if choice == “1”:
                print(“Roman Numeral:”, to_roman(num))
            elif choice == “2”:
                print(“Binary:”, to_binary(num))
            elif choice == “3”:
                print(“Hexadecimal:”, to_hex(num))
            elif choice == “4”:
                print(“Words:”, to_words(num))
            else:
                print(“Invalid choice!”)

        except ValueError:
            print(“Please enter a valid integer.”)

if __name__ == “__main__”:
    main()

Leave a Reply