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":
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":
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.
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.