noob question Letters in words?
Fredrik Lundh
fredrik at pythonware.com
Sat Oct 8 07:56:43 EDT 2005
(re that earlier thread, I think that everyone that thinks that it's a
good thing that certain Python constructs makes grammatical sense
in english should read the previous post carefully...)
Rob Cowie wrote:
> A string can be thought of as a tuple of characters.
footnote: the correct python term is "sequence of characters".
> Tuples support membership testing thus...
>
> choice1 = raw_input("> ")
>
> if '1' or 's' or 'S' in choice1:
> #do something
> elif '2' or 'e' or E' in choice1:
> #do something
>
> It doesn't seem to me to be a good idea; If the input is 'Start',
> option1 is executed, likewise if the input is 'Stop', or any other
> string with 's' in it.
in fact, the first choice is always executed, because
if '1' or 's' or 'S' in choice1:
...
might look as if it meant
if ('1' in choice1) or ('s' in choice1) or ('S' in choice1):
...
but it really means
if ('1') or ('s') or ('S' in choice1):
...
since non-empty strings are true, the '1' will make sure that the entire
expression is always true, no matter what choice1 contains.
> Perhaps a better idea is to present the user with a choice that cannot
> be deviated from, along the lines of...
>
> def main():
> print "1.\tStart"
> print "2.\tSomething Else"
> print "3.\tStop"
>
> x = raw_input()
> if x is '1': print 'Start'
> elif x is '2': print 'Something else'
> elif x is '3': print 'End'
> else: main()
The "is" operator tests for object identity, not equivalence. Nothing
stops a Python implementation from creating *different* string objects
with the same contents, so the above isn't guaranteed to work. (it
does work on current CPython versions, but that's an implementation
optimization, and not something you can rely on).
You should always use "==" to test for equivalence (and you should never
use "is" unless you know exactly what you're doing).
</F>
More information about the Python-list
mailing list