'Python - Converting roman numerals to integers in a loop, ending script with specific character

Very new to Python, i've managed to do some research on Stack Overflow and using the code below, successfully converted roman numerals to integers.

def romanToInt(s):
    d = {'m': 1000, 'd': 500, 'c': 100, 'l': 50, 'x': 10, 'v': 5, 'i': 1}  
    n = [d[i] for i in s.lower() if i in d]  
    return sum([i if i>=n[min(j+1, len(n)-1)] else -i for j,i in enumerate(n)])

print(romanToInt('X'))

What I'm struggling to do however is to get this program to continue to run after the output given so the user can enter the next value. I would also like the program to stop when the user enters the character 'Q'.

Any help would be greatly appreciated

I've done some research on basic loops which I can understand, it's just then incorporating them into code that already exists (such as the code above) which I'm struggling with.



Solution 1:[1]

Note: there are many ways to do what you're asking—it just depends on how you want it to work/what else you might be doing with it.

Asking for input from the user requires the input() function. (It's also a good idea to normalise and test input so it's not case-sensitive and your program doesn't get stuck if users enter something non-sensical, e.g., 'H' here).

If you want to do something until a condition is met (where there's no way of knowing how many iterations that may take), a while loop can be a good option.

while loops can be tricky, though, because if you don't do something that explicitly breaks out of them, you can create an infinite loop and crash your program.

See below, where I show two examples of while loops (the first generally being a better idea than the second).

def romanToInt(s):
    d = {'m': 1000, 'd': 500, 'c': 100, 'l': 50, 'x': 10, 'v': 5, 'i': 1}
    n = [d[i] for i in s.lower() if i in d]
    return sum([i if i>=n[min(j+1, len(n)-1)] else -i for j,i in enumerate(n)])

# this `while` loop explicitly tests a condition each time it runs
text = ''
while text.lower() != 'q':
    print(romanToInt(text))
    text = input("Enter a Roman numeral")



# this `while` loop just runs repeatedly until you explicitly break out of it
# this is often really bad practice
while True:
    # Creates a dialogue box asking the user for input
    text = input("Enter a Roman Numeral")

    if text.lower() != 'q':   # lower() means both 'Q' and 'q' end the loop
        print(romanToInt(text))

    # without the `break` statement inside the `else` block,
    # this creates an infinite loop
    else:
        break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 baileythegreen