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": # false positive if choice == ''
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With