[Tutor] Number Coercion: I swear, I never laid a hand on it!
Remco Gerlich
scarblac@pino.selwerd.nl
Wed, 24 Oct 2001 19:03:46 +0200
On 0, kromag@nsacom.net wrote:
> -------------silly menu script-------------
>
> import os
> import string
> import sys
>
>
> menu_items={'edit': '\windows\command\edit.com',
> 'vim': '\vim\vim57\gvim.exe'}
Note that this won't work; backslashes have a special meaning, they're used
to escape things so you can put special characters in a string (like \n
means newline).
A way to avoid this is to escape the backslashes; use \\ instead of \.
> print 'menu choices'
> print menu_items.keys()
>
> choice = raw_input()
>
> if menu_items.has_key(choice):
> os.system('s%')% menu_items[choice]
> else:
> sys.exit('Sorry, try again.')
>
> ---------end silly menu script-------------
>
> For some reason, I get a problem with:
>
> os.system('s%')% menu_items[choice]
I don't know if this is a typo or what, but the way it is written, it runs
os.system('s%') first. 's%' is a command that probably doesn't exist, and
os.system will return some number.
The '%' operator used on numbers is the modulo operator; Python tries to
interpret menu_items[choice] as another number but fails; it's a string.
This gives a coercion error.
What you meant was both '%s' instead of 's%', and to have the % command
inside the os.system, not outside of it:
os.system('%s' % menu_items[choice])
which happens to be exactly the same thing as
os.system(menu_items[choice])
I think this reply is a bit obfuscated but I have to go, cooking :)
--
Remco Gerlich