[Tutor] Is there an easily or shorter way?

Steven D'Aprano steve at pearwood.info
Mon Dec 15 23:49:29 CET 2014


On Mon, Dec 15, 2014 at 04:25:42PM -0500, Ken G. wrote:
> I am sure there is a better way to refine the following lines.
> 
> Letting x equal a number from 1 to 28, go through 28 separate 'if'
> statements to print a resulting value that equaled the value of x.

Since you only care about the first 28 values, a list or dict is the way 
to go. The two look remarkably similar:

# Using a dict. Replace the dots ... with the rest of the values.
names = {1: "one", 2: "two", 3: "three", ... 28: "twenty-eight"}
print(names[x])

# Using a list. Again, replace the dots.
names = ["zero", "one", "two", "three", ... "twenty-eight"]
print(names[x])


I stress that neither version *quite* works yet. You have to replace the 
dots ... with the rest of the values, which is tedious but not hard.

In the case of the list version, the reason that I add an entry for zero 
is that lists are indexed from zero. That is, given the list:

    L = ['spam', 'eggs', 'cheese', 'toast']

the first entry is written L[0], the second entry L[1] and so forth. 
Although it takes a bit of getting used to, there actually are good 
reasons for that. One advantage of dicts over lists is that you can 
leave gaps while a list must have placeholders for every position:

    {2: "two", 4: "four", 8: "eight"}
    ["", "", "two", "", "four", "", "", "", "eight"]


Of course, as Danny suggested, if you're going to be using this 
seriously for arbitrary numbers, you can't possibly list every single 
one in advance. What if somebody asks for the name of 9274810276523? In 
that case, we need a function that turns a number into an name digit by 
digit:

    nine trillion, two hundred and seventy-four billion, 
    eight hundred and ten million, two hundred and 
    seventy-six thousand, five hundred and twenty-three

Doing this makes a nice little programming exercise, so I will leave it 
to you :-)


-- 
Steven


More information about the Tutor mailing list