Raspberry_Pi_Education_Manual

Notes:

Lesson 3.3: Roman Numerals & data manipulation

def int2roman (number): numeralOrder = [1000,900,500,400,100,90,50,40,10,9,5,4,1] numeralLetters = { 1000 : "M" , 900 : "CM" , 500 : "D" , 400 : "CD" , 100 : "C" , 90 : "XC" , 50 : "L" , 40 : "XL" , 10 : "X" , 9 : "IX" , 5 : "V" , 4 : "IV" , 1 : "I" } result = "" if number < 1 or number > 4999: raise ValueError for value in numeralOrder: while number >= value: result += numeralLetters[value] number -= value return result try : print (int2roman( int ( input ( "Enter an integer (1 to 4999): " )))) except ValueError : print ( "Try again" )

This program introduces the idea of a function. A function groups together commands into a block. It is the basic method by which you can create your own Python commands. Functions can have variables given to them and they can give back an answer once they are finished. They are great for reusing instructions on different data and getting results. In this case, it will take a normal decimal number and give back a sequence of letters that are the Roman equivalent.

The following command runs a number of functions all in one:

print (int2roman( int ( input ( "Enter an integer (1 to 4999): " )))) It prints the result of the function “int2roman”. It is started ( called ) with the result of “int” and “input”. The “int” function is converting the letters you type into a number. The “input” function allows Python to get some numbers from the user. Finally, The characters that the function creates are printed onto the display.

To work out the Roman Numeral equivalent for a number, you just need to keep taking the largest possible Roman number out of the given number, and adding the Roman Numeral to the string as it does so. A string is how computer scientists describe a sequence of characters; letters, numbers and other special symbols Notice that the “numeralLetters” sequence is made from a pair of numbers and letters. This is a particular kind of sequence known as a “ dictionary ”. The order of the entries in the dictionary is not guaranteed to be the same as you enter it. This is so the computer can optimise how the data is stored and give you quick access later. The left part of the dictionary entry is the “ key ”, and can be almost anything. To get the value of the entry (the right-hand part), you can ask for it by the key, using square brackets “[ ]” around the key. The “numeralOrder” is a normal list, where the order is maintained. This is used to break down the number coming into the function, from highest to lowest.

Experiments in Python

89

Made with FlippingBook flipbook maker