[Tutor] changing list index start
Steven D'Aprano
steve at pearwood.info
Sat Sep 11 17:15:42 CEST 2010
On Sat, 11 Sep 2010 11:25:12 pm Rance Hall wrote:
> Thanks everyone for responding, Because this menu structure is
> repeated many times in my code, the ideal solution would have been to
> "set index start = 1" in the beginning of the script.
That is exactly the wrong solution. That will break anything and
everything that assumes "set index start = 0" is applying. Fortunately
Python doesn't allow such a bad "solution".
The right solution is to get rid of all that duplicated code. Put the
menu structure in one place, a function, and then call that function
whenever you need it:
def display_menu(menu):
for i,option in enumerate(menu, 1):
print('%s. %s' % (i, option))
choice = int(input('\nYour Choice? '))
clearscreen(osname)
return choice-1
Now your mainmenu function becomes:
def mainmenu():
# the main menu, in case you can't read the function name
todolist() # why is this here?
menu = ['Clients','Jobs','Billing','Quotes','To Do
Items','Employee','Exit']
calls = [clientsmenu, jobsmenu, billingmenu, quotesmenu,
todomenu, empmenu, quit]
n = display_menu(menu)
calls[n]()
And similarly for your other menus:
def secondmenu():
menu = ['About','Help','Exit']
calls = [aboutmenu, helpmenu, quit]
n = display_menu(menu)
calls[n]()
> something like sysctl variables in Linux perhaps but in this case
> only valid for this program.
>
> Its clear from the responses that this solution is not available in
> python, I wish it were, it would make my life much easier for this
> project.
No, you only *think* it would make your life easier. This is probably
the time to quote Yoda's speech about the Dark Side of the Force
from "The Empire Strikes Back".
Such global settings are "easier, faster, simpler"... for about fifteen
minutes. The right solution is to build reusable building blocks, then
put them together.
[...]
> Lie also referred to my particular case as a valid exception, are
> there enough other such valid exceptions that requesting a feature
> enhancement would gain some traction?
Not a hope in hell.
You have misunderstood Lie's comment. He's talking about the use of an
index *at all*. Normally in Python you shouldn't need to use indexes,
regardless of whether they start with 0 or 1 or 3.1425.... Your example
of a text menu is an exception to the rule (more of a guideline
really) "you shouldn't care about indexes".
--
Steven D'Aprano
More information about the Tutor
mailing list