In Python3 does num+=roman[s[i:i+2]] not throw key error in loop?

I’m trying to understand a function in Python meant to convert Roman numerals to integers. In the following code:


roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
s = "III"
i = 0
num = 0
while i < len(s):
    if i+1<len(s) and s[i:i+2] in roman:
        num+=roman[s[i:i+2]]
        i+=2
    else:
        #print(i)
        num
        num+=roman[s[i]]
        i+=1
print(num)

The if statement somehow gives an answer of 2, but when I think it through it looks like it should only loop through the if statement once and give 1. But when I think it through further and isolate this section I get a key error ‘II’ which makes sense. So how is the loop not throwing this error and giving a value of 2?

Appreciate any and all help!

>Solution :

The first time through the loop, i = 0 and s[i:i+2] = 'II'. 'II' in roman is not true, so we go to the else: block. s[i] = 'I', and roman['I'] = 1, so we add 1 to num, which now equals 1. We also add 1 to i.

The second time through the loop, i = 1 and s[i:i+2] = 'II'. Again, that’s not a key in the dictionary, so we go to the else: block and add roman['I'] to num. So now num = 2. We also add 1 to i.

The third time through the loop, i = 2 and i+1 < len(s) is false. So we go to the else: block. s[i] = 'I' again, so we we add 1 to num again. Now num = 3. We also add 1 to i.

Now i = 3 and the condition while i < len(s): is no longer true, so the loop ends.

We never get a key error because we always check whether II is a key in the dictionary before trying to access roman['II'].

Leave a Reply