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?

2
  • Please format your code by indenting it by 4 spaces. You can also highlight it and press ctrl+k when in the editor. Commented Jul 30, 2017 at 16:23
  • 1
    And that appears to be destructuring syntax. Commented Jul 30, 2017 at 16:24

1 Answer 1

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:]
Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.