0

In a forum I have found this nice function (done by Pixie) converting from Roman to Arabic numbers.

def decoder(r):
    k=r
    if r=="":return "Don't leave the input blank"
    roman,s= {"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},0
    while r!="":
        if r[:2] in roman:a,r=r[:2],r[2:]
        elif r[0] in roman:a,r=r[0],r[1:]
        else: return "Enter proper Decimal/Roman number as input"
        s+=roman[a]
    return s if encoder(int(s))==k else "Not a valid Roman Numeral"


a="MCM"
print(decoder (a.upper))

I am a super newbie of Python, and I do not understand the statement

if r[:2] in roman:a,r=r[:2],r[2:]

I know r[:2] and others are string slicing. What I do not understand is the usage of the commas: a,r=r[:2],r[2:] looks as a tuple but why? Is it an assignment?

Snow
  • 1,058
  • 2
  • 19
  • 47

1 Answers1

0

Python has the ability to assign to multiple values on the sample line...

In this case, I am also moving the assignment lines to a new, indented line under the if and elif statements.

if r[:2] in roman:
    a,r = r[:2], r[2:]

elif r[0] in roman:
    a,r = r[0], r[1:]

The first assignment line is the same as:

a = r[:2]
r = r[2:]

The second one is the same as:

a = r[0]
r = r[1:]
E. Ducateme
  • 4,028
  • 2
  • 20
  • 30
  • Maybe in this case it happens to have the same effect. However, `a,b=b,a` is not the same as `a=b` followed by `b=a` – tonypdmtr Jul 30 '17 at 17:17
  • @tonypdmtr the code shown by the OP does not do what you are suggesting... for sake of argument, we could generalize `r[:2]` to be `x` and `r[2:]` to be `y` and thus `a, r = x, y` would be equivalent to `a = x` and `r = y` NOT the variable swapping exercise you suggest. – E. Ducateme Jul 30 '17 at 17:23