tags:

views:

91

answers:

3

Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase?

elif choice == "m":
+12  A: 

One of

elif choice in ("m", "M"):
elif choice in "mM":
elif choice == 'm' or choice == 'M':
elif choice.lower() == 'm':

In terms of maintainability, the 4th alternative is better when you want to extend to case-insensitive comparison of multiple-letter strings, as you need to provide all 2N possibilities in the 1st and 3rd alternatives. The 2nd alternative only works properly for single-character strings.

With the 4th alternative it is also impossible to miss a case when you want to change the 'm' to other letters.

In terms of efficiency, the 2nd alternative is the most efficient, and then the 1st, and then the 3rd and finally the 4th. This is because the 3nd alternative involves more operations; and while function calling and getting attribution is slow in Python so both makes the 4th alternative relatively slow.

See http://pastie.org/1230957 for the disassembly and timeit result.

Of course unless you're doing this comparison 10 million times there is no perceivable difference between each one.

KennyTM
The OP already said this was for a menu display, that is, user input. Why the obsession with timeit?
Ned Batchelder
@KennyTM: I disagree about the 3rd option being the 3rd in terms of efficiency. Due to lazy evaluation and the fact that the other operations intrinsically involve equality comparisons anyways, it just as fast or faster than the other ones. But it is also the least pythonic one.
kaloyan
@kaloyan You should really learn to read `timeit` results. They're incredibly helpful for settling confusion concerning efficiency. They've corrected mistakes in my intuition on more than one occasion.
aaronasterling
@aaronasterling: Thank you for the indispensable words of indescribable wisdom. I will now go and really learn to read `timeit` results :|
kaloyan
@kaloyan, the indescribable wisdom is not in my words but in the timeit results Given that you are casually stating that your intuition trumps concrete data that makes perfect sense once you read the bytecode listings, I would say that you should drop the attitude and learn to read a timeit result **and** bytecode listings. :) HTH!
aaronasterling
@aaronasterling: You are right. My bad.
kaloyan
+6  A: 
elif choice.lower() == "m":
Ignacio Vazquez-Abrams
A: 

This way would be both explicit and very succinct:

    elif choice in {'m', 'M'}:

Of course, to express it this way requires Python 2.7 or 3.x which support set literals. I don't know how it compares efficiency-wise to the other answers, but doubt that matters much for a case like this.

martineau