1

Practicing coding by trying to make a Roman Numerals Converter. I'm trying to make a method that contains a while loop that calls for the user's input. I am confused as how to go about doing so.

Here is the created class with init method.

class RomanNumeral: 
    """A class to represent our roman numerals or integers."""
    def __init__(self, user_input): 
        """Initializes the user's input, a counter, and standard values for each roman numeral."""
        self.input = user_input
        self.rom_dict = {u'M\u0305': 1000000, u'C\u0305M\u0305': 900000, u'D\u0305': 500000, \
                    u'C\u0305D\u0305': 400000, u'C\u0305': 100000, u'X\u0305C\u0305': 90000, \
                    u'L\u0305': 50000, u'X\u0305L\u0305': 40000, u'X\u0305': 10000, \
                    u'I\u0305X\u0305': 9000, u'V\u0305': 5000, u'I\u0305V\u0305': 4000, 'M': 1000, \
                    'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, \
                    'IX': 9, 'V': 5, 'IV': 4, 'I': 1}

Rest of the code for reference.


    def rom_or_int(self):
                """Checks if user input is a roman numeral, integer, or not."""
                # Checks if user input is a integer
                if self.input.isdigit():
                    number = int(self.input)
                    print("The equivalent Roman Numeral is: " + self.int_to_rom(number) + ".\n")
                # Checks if user input is a roman numeral, if so run method 
                elif self.isroman():
                    self.rom_to_int()
                # If not, print this statement
                else:
                    print("Entry is neither in roman numerals or an integer.\n")

        def isroman(self):
            """Checks if user input is a roman numeral."""
            for i in self.input:
                if i not in self.rom_dict.keys():
                    return False
            return True

        def int_to_rom(self, number):
            """Takes the user input of integer and converts it to Roman Numerals."""
            # Create a list of tuples for the standard values of the roman numerals
            roman_numeral = "" # empty string to create roman numeral

            for k,v in self.rom_dict.items():
                if number - v >= 0: # finds the greatest integer value that can be subtracted from input
                    x = number // v # x is the number of times the current roman numeral appears
                    number -= x*v # subtract the input from the roman numeral to be added to the string
                    roman_numeral += x * k # the string is now x amount of the roman numeral
            return roman_numeral

        def rom_to_int(self): # next() function? LXD and DXL give wrong answers.
            """Takes in user_input in roman numerals and return the equivalent integer."""
            rom_dict = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}

            integer = 0 # counter

            # Iterates the user's input
            for i in range(len(self.input)):
                roman_value = rom_dict[self.input[i]] # checks the integer value of the current iteration

                # if the subceding roman numeral is of greater value, subtract
                if i+1 < len(self.input) and roman_value < rom_dict[self.input[i+1]]:
                    integer -= roman_value
                else: # if not add
                    integer += roman_value

            # checks to see if this is a valid Roman Numeral by comparing to the output of the int_to_rom method
            check_value = self.int_to_rom(integer)
            if self.input == check_value:
                print("The equivalent integer value is: " + str(integer) + ".\n")
                return integer
            else:
                print("This is not a proper roman numeral.\n")

Currently, I'm using this way of asking for the user's input

if __name__ == '__main__':
    while True:
        print("Press 'Enter' without an input to exit program.")
        user_input = (input("Enter a Roman Numeral or integer to convert: "))
        if user_input == "":
            exit()
        x = RomanNumeral(user_input)
        x.rom_or_int()

I was thinking about doing this:

def user_input(self):

    while True:
            print("Press 'Enter' without an input to exit program.")
            user_input = (input("Enter a Roman Numeral or integer to convert: "))
            if user_input == "":
                exit()
            x = RomanNumeral(user_input)
            x.rom_or_int()

But, I don't know how to go about instantiating the class to utilize the function.

1 Answer 1

1

This should work for you.

Two notes:

  • You named the a function and a variable the same name, user_input this can cause unforeseen errors
  • Replaced exit() with return since we are running in a function now
def user_input(self):

    while True:
            print("Press 'Enter' without an input to exit program.")
            ui = (input("Enter a Roman Numeral or integer to convert: "))
            if ui == "":
                return  # return > exit(), because this is in a function
            x = RomanNumeral(ui)
            x.rom_or_int()
            # will continue to loop, until user enters a null string as input

Keep in mind, this functoin will only exit if the user enters a null string

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, but dumb question: I just am confused as to how to call the function in the name/main block. The function already instantiates the function. I can't simply use user_input().
Edit: Nevermind. I figured it out. Turn it into a class method. Thanks for the help :)
Glad we could get it figured out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.