[Tutor] roman to arabic

Alan Gauld alan.gauld at btinternet.com
Mon Feb 27 02:45:03 CET 2012


On 26/02/12 23:29, Sukhpreet Sdhu wrote:

> import string

Are you using a very old versioon opf python?
If not you should not use string.
The built in string methods can do everything you
want without resorting to string.

> print "Welcome to the numeric conversion program"
> print "Please enter command"
> data=raw_input()
> now = 0
> previous = 0
> total = 0
> if data == "r":
>      print "Enter roman numeric to convert in arabic"
>      roman_numeric=string.swapcase(raw_input("Enter the Roman Numeral to convert to arabic"))

Are you sure you want swapcase()? I'd have thought uppercase()
would be more effective given the tests below.

Using built in methods that line becomes:

roman_numeric=raw_input("Enter the Roman Numeral to convert to 
arabic").uppercase()


>   if roman_numeric == ("M" or "D" or "L" or "C" or "L" or "X" or "V" or "I"):

This is just wrong!
The parenthesised list will evaluate to True so you are testing  if the 
variable is True, which it will be if not empty.

You want:

if roman_numeric in ("M","D","L","C","L","X","V","I"):

>       Length = len(roman_numeric) - 1

If the variable is one of the items in your list it is only 1 char long 
so you re setting Length to zero. Is that what you want?

>       i = roman_numeric[Length]

If you really want to extract the last digit use a -1 index.
In which case you dshould do the same for the check on valid values...


>       if i == "M":
>           now = 1000
>           if i == "D":
>               now = 500

Are you sure you want this structure?
It would look a lot neater using elif

        if i == "M":
            now = 1000
        elif i == "D":
            now = 500
        elif i == "C":
             now = 100

But better still would be to use a dictionary:

values = { 'I':1, 'V':5, 'X':10,...'D':500, 'M':1000 }

now = values[i]

>                                   acc = now
>                                   if (previous>= now):
>                                       total += acc-prvious

spelling error in prvious

>                                       print "The total is",total
>                                       if (previous<= now):
>                                           total += acc-prevous
>                                           print "The total is",total
>                                           else :

This else doesn't line up with any if.

 >                                               if data == "a" :

else:
    if <cond>:

could just be

elif <cond>:

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list